当前位置:网站首页>qt批量操作控件,并设置信号槽
qt批量操作控件,并设置信号槽
2022-07-28 05:25:00 【小土同学!】
前言
qt中很多情况都需要对控件进行批量操作,又想对容器进行单独操作。如果用代码创建控件,则无法单独拿到控件的对象名,如果在ui文件中拖动创建控件,则无法批量操作。网上查了一些资料,感觉都写的非常繁琐,于是自己尝试写了一下,主要有两种思路
情况一、代码创建控件,对控件批量操作和单独操作,并设置信号槽
思路:使用QVector模板类,将控件添加到容器
代码如下:
//创建容器
QVector<QPushButton *> btnList;
for (int i=0; i<6; i++) {
//添加代码创建的按钮
btnList.push_back(new QPushButton(this));
}
//对容器批量操作
for (int i=0; i<btnList.size(); i++) {
btnList[i]->setText(QString("按钮 %1").arg(i+1));
btnList[i]->move(100,(i+1)*50);
//设置信号槽
connect(btnList[i],&QPushButton::clicked,this,[=](){
QMessageBox::about(this,"提示",QString("这是按钮 %1").arg(i+1));
});
}
你可以使用QVector容器,也可以使用QList列表,使用方法大致一样。在设置信号槽的时候,我们也可以轻易获取该按钮的序号,然后让其跳转到特定的槽。
效果如下:

但ui文件里的控件也可以这样操控,但如果在ui文件中有太多的按钮时,一个个添加也很麻烦,下面看情况二
情况二、ui文件中创建控件,对控件批量操作和单独操作,并设置信号槽
思路:通过父控件来获取内部的按钮控件,将这些空间存入QList或者QVector中,再进行操控
//获取widget中所有的按钮
QList<QPushButton *> btnsList = ui->widget->findChildren<QPushButton *>();
//对容器批量操作
for (int i = 0; i<btnsList.size(); i++)
{
btnsList[i]->setText(QString("这是按钮 %1").arg(i+1));
//设置信号槽
connect(btnsList[i],&QPushButton::clicked,this,[=](){
QMessageBox::about(this,"提示",btnsList[i]->text());
});
}
注意:按钮在列表中的顺序是以递归方式进行的,目前猜测的顺序是,从左到右,从上到下,左边按钮的名称是我创建的顺序。这一点需要格外注意

码字不易,如果这篇博客对你有帮助,麻烦点赞收藏,非常感谢!有不对的地方,可以评论区交流。
边栏推荐
- RS232 RS485 RS422 communication learning and notes
- Design and analysis of contactor coil control circuit
- 机器学习笔记 5 —— Logistic Regression
- ClickHouse 中的公共表表达式CTE
- 初学者进行传感器选型
- 低功耗设计-Power Switch
- Pytorch learning notes 3 - datasets & dataloaders & transforms
- Bert bidirectional encoder based on transformer
- In asp Usage of cookies in. Net
- TVs tube parameters and selection
猜你喜欢

Ship detection in SAR image based on yolov5

A NOVEL DEEP PARALLEL TIME-SERIES RELATION NETWORK FOR FAULT DIAGNOSIS

Pycharm2019 set editor theme and default code

clock tree分析实例

Low power design isolation cell

Learning notes on hardware circuit design 2 -- step-down power circuit

Bag of Tricks训练卷积网络的技巧

Measure computer battery capacity

Best practices to ensure successful deployment of Poe devices

Selection of PLC
随机推荐
Trouble encountered in cable testing -- a case study of a manufacturer?
Measure computer battery capacity
Mae mask self encoding is scalable learning
ICC2(四)Routing and Postroute Optimization
An example of bill printing
Efficient Net_V2
Systemmediasize startup option added in esxi 7.0 update 1C
mixup_ratio
A NOVEL DEEP PARALLEL TIME-SERIES RELATION NETWORK FOR FAULT DIAGNOSIS
Pycharm2019 set editor theme and default code
t-SNE降维可视化
VB OCX applied to Web
set_clock_groups
Triode design, understanding saturation, linear region and cut-off region
ICC2(一)Preparing the Design
set_multicycle_path
Word邮件合并功能详解:合并后生成多个word文档,删除空白页
Pytorch learning notes
What is the AEM testpro cv100 and fluke dsx-8000 of category 8 network cable tester?
Pytorch learning notes 2 - about tensor