Qt5最新特性、最高效写法 只查找一级子控件
QList listBtn = ui->gbSel->findChildren(QString(),Qt::FindDirectChildrenOnly);
for(int i=0;i<listBtn.count();++i)//++i比i++效率高,i++需要创建临时变量加1
{
connect(listBtn[i],&QPushButton::clicked,[=]{selCX(i);});
}
QT5 写法,也是利用lambda表达式来实现
for(int i=0;igbSel->layout()->count();++i)//++i比i++效率高,i++需要创建临时变量加1
{
QWidget *widget = ui->gbSel->layout()->itemAt(i)->widget();
QPushButton *btn = qobject_cast(widget);
if(btn!=nullptr)
{
connect(btn,&QPushButton::clicked,[=]{
selCX(i);
});
}
}
QT4 简洁写法
QSignalMapper *mapper = new QSignalMapper(this);
for(int i=0;igbSel->layout()->count();++i) //++i比i++效率高,i++需要创建临时变量加1
{
QWidget *widget = ui->gbSel->layout()->itemAt(i)->widget();
QPushButton *btn = qobject_cast(widget);
if(btn!=nullptr)
{
connect(btn,SIGNAL(clicked()),mapper,SLOT(map()));
mapper->setMapping(btn,i);
}
}
connect(mapper,SIGNAL(mapped(int)),this,SLOT(selCX(int)));文章来源地址https://www.toymoban.com/news/detail-800936.html
QT4 写法,比较好理解的,用到QSignalMapper
QSignalMapper *mapper = new QSignalMapper(this);
connect(ui->cx1,SIGNAL(clicked()),mapper,SLOT(map()));
connect(ui->cx2,SIGNAL(clicked()),mapper,SLOT(map()));
connect(ui->cx3,SIGNAL(clicked()),mapper,SLOT(map()));
connect(ui->cx4,SIGNAL(clicked()),mapper,SLOT(map()));
connect(ui->cx5,SIGNAL(clicked()),mapper,SLOT(map()));
connect(ui->cx6,SIGNAL(clicked()),mapper,SLOT(map()));
connect(ui->cx7,SIGNAL(clicked()),mapper,SLOT(map()));
mapper->setMapping(ui->cx1,0);
mapper->setMapping(ui->cx2,1);
mapper->setMapping(ui->cx3,2);
mapper->setMapping(ui->cx4,3);
mapper->setMapping(ui->cx5,4);
mapper->setMapping(ui->cx6,5);
mapper->setMapping(ui->cx7,6);文章来源:https://www.toymoban.com/news/detail-800936.html
connect(mapper,SIGNAL(mapped(int)),this,SLOT(selCX(int)));
到了这里,关于Qt 遍历多个按钮单击信号带参数,绑定到一个槽的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!