如何获得哪个QradioButton调用SLOT

gin*_*ina 2 c++ qt qt4

我创建了几个QradioButton并连接到同一个SLOT.在插槽中,我想知道哪个QradioButton调用插槽并执行相关操作.我发现使用qobject_cast和QObject :: sender()有一种方法,但它似乎不起作用.这是代码:

头文件:

class dialoginput : public QDialog
{
    Q_OBJECT

public:
    dialoginput(QWidget *parent = 0);
    QRadioButton *radio1;
    QRadioButton *radio2;
    QRadioButton *radio3;
private slots:
    void setText_2();
private:
    QLabel *label_0_0;
    QLabel *label_1;
};
Run Code Online (Sandbox Code Playgroud)

主文件:

dialoginput::dialoginput(QWidget *parent): QDialog(parent){

    label_0_0 = new QLabel("label_1:");
    label_1 = new QLabel;  

    QWidget *window = new QWidget;
    QVBoxLayout *windowLayout = new QVBoxLayout;

    QGroupBox *box = new QGroupBox("Display Type");
    radio1 = new QRadioButton("3");
    radio2 = new QRadioButton("5");
    radio3 = new QRadioButton("9");
    QVBoxLayout *radioLayout = new QVBoxLayout;

    connect(radio1,SIGNAL(clicked()),this,SLOT(setText_2()));
    connect(radio2,SIGNAL(clicked()),this,SLOT(setText_2()));
    connect(radio3,SIGNAL(clicked()),this,SLOT(setText_2()));

    radioLayout->addWidget(radio1);
    radioLayout->addWidget(radio2);
    radioLayout->addWidget(radio3);

    box->setLayout(radioLayout);

    windowLayout->addWidget(box);
    windowLayout->addWidget(label_0_0);
    windowLayout->addWidget(label_1);

    window->setLayout(windowLayout);
    window->show();

}
void dialoginput::setText_2(){

    QObject *object = QObject::sender();
    QRadioButton* pbtn = qobject_cast<QRadioButton*>(object);
    QString name = pbtn->objectName();

    label_1->setText(name);

    if(!QString::compare(name, "3")){       
    }
    else if(!QString::compare(name, "5")){
    }
    else if(!QString::compare(name, "9")){
    }

}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    dialoginput *input = new dialoginput();

    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)

ere*_*der 5

即使使用该sender()方法解决了您的问题,我也不建议使用它.问题是,信号和插槽设计用于分隔发射器和接收器.接收器不需要知道哪些对象,甚至什么类型的对象都可以触发其插槽.当您使用时sender(),您依赖于接收器知道触发其插槽的所有对象的事实.如果将来发生变化怎么办?

你应该看一下QSignalMapper,它专门针对这种需求而设计.在文档中有很好的例子.