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

Qt5最新特性、最高效写法 只查找一级子控件

QList listBtn = ui->gbSel->findChildren(QString(),Qt::FindDirectChildrenOnly);

for(int i=0;i

{

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

你可能感兴趣的:(qt,开发语言,c++)