(Qt) Create signal from QButtonGroup of PushButtons?

时光毁灭记忆、已成空白 提交于 2019-12-08 08:34:53

问题


I am so confused on how this whole thing works.

I have some pushbuttons that I put into a group like this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddSlotsToGroup();
}

void MainWindow::AddSlotsToGroup()
{
    QButtonGroup* group = new QButtonGroup(this);
    group->addButton(ui->slot_0);
    group->addButton(ui->slot_1);
    //...
}

And I want to create a slot that gets the id of the button that was clicked in that group. (Sorry if I explained that poorly :( )

So this is what I did (pure guess after googling)

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddSlotsToGroup();
    connect(QPushButton* group, SIGNAL(buttonClicked(int)), this, SLOT(onGroupButtonClicked(int)));
}

void MainWindow::onGroupButtonClicked(int id)
{
    qDebug() << id;
}

And to no surprise, I got an error saying group is an undeclared identifier and that QPushButton was an illegal use etc.

I hate to say that I have only used signals/slots from the designer window, so I really just need this one thing, and then I'm set for the future. :)

Thanks for your time. :)


回答1:


Try the following:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddSlotsToGroup();
}

void MainWindow::AddSlotsToGroup()
{
    QButtonGroup* group = new QButtonGroup(this);
    group->addButton(ui->slot_0);
    group->addButton(ui->slot_1);
    //...
    connect(group, SIGNAL(buttonClicked(int)),
            this, SLOT(onGroupButtonClicked(int)));
}

By the way, you need to learn C++ first to master Qt.




回答2:


First you need to include QButtonGroup.

#include <QButtonGroup>

Your connection is malformed, please save "group" pointer as class member first and then use following:

connect(group, SIGNAL(buttonClicked(int)), this, SLOT(onGroupButtonClicked(int)));


来源:https://stackoverflow.com/questions/17647823/qt-create-signal-from-qbuttongroup-of-pushbuttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!