qt动态添加多个button按钮简单,难题是如何对动态的按钮添加响应函数,本文解决方案有两个
方法一:使用信号-槽函数
QString strTemp;int nCol = 6;//一行有6个for(int i = 0; i < CZList.size(); i++){int ii = i / nCol;int jj = i % nCol;strTemp = QString("%1").arg(CZList[i].nnumber);QPushButton *pbtn1= new QPushButton(strTemp);pbtn1->setObjectName(strTemp);//关联信号槽函数//connect(pbtn1,SIGNAL(clicked()),this,SLOT(onButtonCliked()));//旧写法connect(pbtn1,&QPushButton::clicked,this,&CSelectZhanTaiNumber::onButtonCliked);m_pButtonList.push_back(pbtn1);pLayout->addWidget(pbtn1, ii, jj);}
void onButtonCliked()
{QPushButton *btn = qobject_cast<QPushButton*>(sender());//获取按钮显示文本QString text = btn->text();//获取按钮对象名称QString name = sender()->objectName();//do something在这里进行其他事项处理qDebug()<<"xianshi"<<text;qDebug()<<"name:"<<name;
}
方法二:使用事件过滤器
创建动态按钮
int nCol = 6;//一行有6个按钮QString strTemp;for(int i = 0; i < CZList.size(); i++){int ii = i / nCol;int jj = i % nCol;strTemp = QString("%1").arg(CZList[i].nnumber);QPushButton *pbtn1= new QPushButton(strTemp);pbtn1->setObjectName(strTemp); pbtn1->installEventFilter(this);m_pButtonList.push_back(pbtn1);pLayout->addWidget(pbtn1, ii, jj);}
重写事件过滤器
bool xx::eventFilter(QObject *obj, QEvent *e)
{//使用事件过滤器,就不用添加多个connect了,方便2024.1.30if (getButoonStatus(obj)){if (e->type() == QEvent::MouseButtonPress){QMouseEvent* mouseEv = static_cast<QMouseEvent*>(e);QString qs = QString("name: %3").arg(obj->objectName());qDebug() << qs;return true;}}return QWidget::eventFilter(obj, e);
}
bool XX::getButoonStatus(QObject *obj)
{bool bRet = false;for(int i = 0; i < m_nNumber; i++){if(m_pButtonList[i] == obj){bRet = true;}}return bRet;
}