LoginSignup
2
2

More than 5 years have passed since last update.

Qt5.3を用いて押された checkboxにより処理を振り分ける

Last updated at Posted at 2014-08-17

Qt初心者です 10年以上昔に出版された Qt3の書籍 (Qtプログラミング24時間集中講座)を見ながら格闘しています 何しろ入手できる資料が少く困っています
自分のブログにも掲載しました

sender()の使用

mymainwindow.h
#ifndef MYMAINWINDOW_H
#define MYMAINWINDOW_H

#include <QMainWindow>
#include <QtGui>
#include <QtWidgets>

class MyMainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MyMainWindow(QWidget *parent = 0);
    ~MyMainWindow();
    QCheckBox *chk[4];
public slots:
    void dispatch();
};

#endif // MYMAINWINDOW_H
mymainwindow.cpp
#include "mymainwindow.h"

MyMainWindow::MyMainWindow(QWidget *parent): QMainWindow(parent)
{
    this->resize(400,200);
    QVBoxLayout *layout = new QVBoxLayout();
    QVBoxLayout *layout1 = new QVBoxLayout();
    QGroupBox *group = new QGroupBox(this);
    group->resize(400,200);
    group->setLayout(layout);
    group->setAlignment(Qt::AlignHCenter);
    group->setCheckable(true);
    QButtonGroup *bg = new QButtonGroup(this);
    chk[1] = new QCheckBox("CAG", this);
    chk[2] = new QCheckBox("PCI", this);
    chk[3] = new QCheckBox("TAVI", this);
    group->setTitle("Cardiology");
    layout1->addWidget(group);
    for (int i=1; i<4; i++) {
        bg->addButton(chk[i]);
        layout->addWidget(chk[i]);
    }
    group->setStyleSheet("*{background-color:rgb(0, 0, 255); padding: 7px ; color:red;}");
    this->setStyleSheet("*{background-color:rgb(150,147,88); padding: 7px ; color:brown}");
    for (int i=1; i<4; i++) {
        connect(chk[i], SIGNAL(clicked()), this, SLOT(dispatch()));
    }
}

MyMainWindow::~MyMainWindow()
{

}

void MyMainWindow::dispatch() {
    QCheckBox *checkbox = static_cast<QCheckBox *>(sender());
    QString msg = checkbox->text();
    msg += " was pushed!";
    QMessageBox mbox;
    mbox.setText(msg);
    mbox.setIcon(QMessageBox::Warning);
    mbox.setDetailedText("This message was automatically dispatched.");
    mbox.exec();
}

結果
これにより、ボタンを押せば、それぞれのボタンテキストがメッセージボックスに表示されます
もっとスマートな解説が英語ですが、ここにあるのですが、初心者の自分には難しくて こんな姑息的な手段を取りました

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2