简体   繁体   English

(Qt)从QButtonGroup的PushButton创建信号?

[英](Qt) Create signal from QButtonGroup of PushButtons?

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. 我想创建一个插槽,获取该组中单击的按钮的ID。 (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. 毫不奇怪,我得到一个错误,说组是一个未声明的标识符,而且QPushButton是非法使用等。

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. 谢谢你的时间。 :) :)

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. 顺便说一下,你需要先学习C ++才能掌握Qt。

First you need to include QButtonGroup. 首先,您需要包含QButtonGroup。

#include <QButtonGroup>

Your connection is malformed, please save "group" pointer as class member first and then use following: 您的连接格式不正确,请先将“group”指针保存为类成员,然后使用以下命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM