Qt通过界面编辑器可以快速制作界面,但有的界面还是需要动态创建(删除)一些控件。
下面就以在界面中添加PushButton为例,完成相关操作。
首先在界面中放置一个QGroupBox及两个按钮,效果如下图所示:
通过点击add按钮添加3个水平放置的QPushbutton,点击delete删除
dynamicCreationAndDeletion.h代码如下:
#ifndef DYNAMICCREATIONANDDELETION_H #define DYNAMICCREATIONANDDELETION_H #include <QMainWindow> namespace Ui { class dynamicCreationAndDeletion; } class dynamicCreationAndDeletion : public QMainWindow { Q_OBJECT public: explicit dynamicCreationAndDeletion(QWidget *parent = 0); ~dynamicCreationAndDeletion(); private slots: void on_pushButton_add_clicked(); void on_pushButton_delete_clicked(); private: QStringList buttonNameList; QString hBoxLay = "HBL"; Ui::dynamicCreationAndDeletion *ui; }; #endif // DYNAMICCREATIONANDDELETION_H
dynamicCreationAndDeletion.c代码如下:
#include "dynamiccreationanddeletion.h" #include "ui_dynamiccreationanddeletion.h" dynamicCreationAndDeletion::dynamicCreationAndDeletion(QWidget *parent) : QMainWindow(parent), ui(new Ui::dynamicCreationAndDeletion) { ui->setupUi(this); buttonNameList.append("pb1"); buttonNameList.append("pb2"); buttonNameList.append("pb3"); } dynamicCreationAndDeletion::~dynamicCreationAndDeletion() { delete ui; } void dynamicCreationAndDeletion::on_pushButton_add_clicked() { //创建水平布局,用于设置按钮的排列顺序 QHBoxLayout * hBoxLayout = new QHBoxLayout(); hBoxLayout->setObjectName(hBoxLay); foreach(QString buttonName,buttonNameList) { QPushButton *pButton = new QPushButton(buttonName,ui->groupBox_pB); pButton->setObjectName(buttonName); pButton->setText(buttonName); hBoxLayout->addWidget(pButton); } ui->groupBox_pB->setLayout(hBoxLayout); } void dynamicCreationAndDeletion::on_pushButton_delete_clicked() { foreach(QString buttonName, buttonNameList) { //获取groupBox中的Pushbutton QPushButton *pushBt = ui->groupBox_pB->findChild<QPushButton*>(buttonName); //删除pushButton delete pushBt; } //删除水平布局,如果此处不删除,会使得第二次添加相同名称的QPushbutton时失败 QHBoxLayout *HBoxlay = ui->groupBox_pB->findChild<QHBoxLayout*>(hBoxLay); delete HBoxlay; }