Qt 遍历多个按钮单击信号带参数,绑定到一个槽

发布时间:2024年01月18日

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)));

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);

connect(mapper,SIGNAL(mapped(int)),this,SLOT(selCX(int)));

文章来源:https://blog.csdn.net/zhouhui1982/article/details/135654960
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。