如下图所示,点击左侧按钮时,删除原有的3组控件,并生成6组控件;点击右侧按钮时,删除原有的6组控件,并生成3组控件。
图1-1 动态生成和删除控件
二、删除动态控件方法
删除动态控件之前,需要知道相关QWidget中的所有控件类型,**使用QWidget的findChildren<控件类型*>()找出对应类型的所有控件,并逐一删除**,例如下方代码所示,为删除widget中的所有QLabel控件,利用此方法可删除widget中的所有控件。
QList<QLabel*> listLabel = ui->widget->findChildren<QLabel*>();//找出所有label控件
foreach (QLabel *label, listLabel)
{
delete label;//删除label控件
}
三、工程代码
1.工程文件
工程文件如下图所示
图3-1 工程文件
2.文件代码
界面文件deletedynamiccontrol.ui
图3-2 界面布局
头文件deletedynamiccontrol.h
#pragma execution_character_set("utf-8")
#ifndef DELETEDYNAMICCONTROL_H
#define DELETEDYNAMICCONTROL_H
#include <QWidget>
#include <QLabel>
#include <QCheckBox>
#include <QComboBox>
#include <QGridLayout>
QT_BEGIN_NAMESPACE
namespace Ui { class DeleteDynamicControl; }
QT_END_NAMESPACE
class DeleteDynamicControl : public QWidget
{
Q_OBJECT
public:
DeleteDynamicControl(QWidget *parent = nullptr);
~DeleteDynamicControl();
private slots:
void on_pbGenerate1_clicked();
void on_pbGenerate2_clicked();
private:
Ui::DeleteDynamicControl *ui;
struct ControlGroup
{
ControlGroup() {}
QLabel *label;
QCheckBox *check;
QComboBox *combo;
};
QList<ControlGroup*> listControlGroup;
void GenerateControl(const int &iNum);
};
#endif // DELETEDYNAMICCONTROL_H
源文件deletedynamiccontrol.cpp
#include "deletedynamiccontrol.h"
#include "ui_deletedynamiccontrol.h"
DeleteDynamicControl::DeleteDynamicControl(QWidget *parent)
: QWidget(parent)
, ui(new Ui::DeleteDynamicControl)
{
ui->setupUi(this);
GenerateControl(8);//默认生成8组控件
}
DeleteDynamicControl::~DeleteDynamicControl()
{
delete ui;
}
void DeleteDynamicControl::on_pbGenerate1_clicked()
{
GenerateControl(6);//点按钮1,生成6组控件
}
void DeleteDynamicControl::on_pbGenerate2_clicked()
{
GenerateControl(3);//点按钮2,生成3组控件
}
void DeleteDynamicControl::GenerateControl(const int &iNum)
{
//删除已有的控件
listControlGroup.clear();
QList<QLabel*> listLabel = ui->widget->findChildren<QLabel*>();
foreach (QLabel *label, listLabel)
{
delete label;
}
QList<QCheckBox*> listCheck = ui->widget->findChildren<QCheckBox*>();
foreach (QCheckBox *check, listCheck)
{
delete check;
}
QList<QComboBox*> listCombo = ui->widget->findChildren<QComboBox*>();
foreach (QComboBox *combo, listCombo)
{
delete combo;
}
QList<QGridLayout*> listLayout = ui->widget->findChildren<QGridLayout*>();
foreach (QGridLayout *layout, listLayout)
{
delete layout;
}
//生成控件
QGridLayout *layout=new QGridLayout;
for(int i=0;i<iNum;i++)
{
ControlGroup *control=new ControlGroup;
control->label=new QLabel;
control->label->setText(tr("输出") + QString::number(i));
layout->addWidget(control->label,i,0,Qt::AlignHCenter);
control->check=new QCheckBox;
layout->addWidget(control->check,i,1,Qt::AlignHCenter);
control->combo=new QComboBox;
control->combo->addItems({tr("高电平"),tr("低电平")});
layout->addWidget(control->combo,i,2,Qt::AlignHCenter);
listControlGroup.append(control);
}
ui->widget->setLayout(layout);
}
版权归原作者 99.999...% 所有, 如有侵权,请联系我们删除。