c++ - How to get which QradioButton invoke the SLOT -
i create several qradiobutton , connect same slot. in slot, want know qradiobutton invoke slot , related action. found there way using qobject_cast , qobject::sender(), seems not work. here code:
header file:
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; };
main file:
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(); }
you create separate wrapper slots each radio button, passes information function want call. this: -
class dialoginput : public qdialog { q_object public: qradiobutton *radio1; qradiobutton *radio2; qradiobutton *radio3; private slots: void radio1selected() { settext_2(1); } void radio2selected() { settext_2(2); } void radio3selected() { settext_2(3); } private: void settext_2(int id);
};
then connect each radio button: -
connect(radio1,signal(clicked()),this,slot(radio1selected())); connect(radio2,signal(clicked()),this,slot(radio2selected())); connect(radio3,signal(clicked()),this,slot(radio3selected()));
now when settext_2 called, id represent selected radio button.
Comments
Post a Comment