多个QPushbutton绑定同一个槽函数,槽函数通过sender判断点击的按钮。
int i = 0; QString str("pushButton %1"); QPushButton* pushButton; for (i = 0; i<16; ++i) { pushButton = new QPushButton(str.arg(i + 1), widget); pushButton->setMinimumSize(pushButton->size()); this->m_pSCVLayout->addWidget(pushButton); pushButton->setObjectName(QString::number(i+1)); connect(pushButton, SIGNAL(clicked()), this, SLOT(OnButrtonClickSlot2())); }
槽函数
void OnButrtonClickSlot2() { QPushButton* btn = (QPushButton*)sender(); qDebug() << "id:" << btn->objectName(); }
输出
id: "1" id: "2" id: "3" id: "4" id: "5" id: "6" id: "7" id: "15" id: "16" id: "13" id: "11"