Source File
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
{
ui->setupUi(this);
layout = new QVBoxLayout;
containWidget = new QWidget;
for (int i = 0; i < 1; ++i)
{
QLabel *label = new QLabel();
QPixmap pixmap;
pixmap.load(":/timg.jpg");
label->setPixmap(pixmap);
layout->addWidget(label);
}
containWidget->setLayout(layout);
ui->scrollArea->setWidgetResizable(true);
ui->scrollArea->setWidget(containWidget);
//this->setCentralWidget(ui->scrollArea);
connect(ui->AddBottun,SIGNAL(clicked(bool)),SLOT(addWidget()));
connect(ui->DelButton,SIGNAL(clicked(bool)),SLOT(delWidget()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::addWidget()
{
for (int i = 0; i < 1; ++i)
{
QLabel *label = new QLabel();
QPixmap pixmap;
pixmap.load(":/timg.jpg");
label->setPixmap(pixmap);
layout->addWidget(label);
}
}
void MainWindow::delWidget()
{
/* //单次删除控件
QLabel *fm = ui->scrollArea->findChild<QLabel*>(); //找到指定名称的控件
layout->removeWidget(fm);
fm->deleteLater();
*/
//删除所有Label 子控件
QList<QLabel *> labelList= ui->scrollArea->findChildren<QLabel *>();
for(int i=0;i<labelList.length();++i)
{
QLabel *fm =labelList.at(i);
layout->removeWidget(fm);
fm->deleteLater();
}
}
head File
#include <QMainWindow>
#include<qlayout.h>
#include <qlabel>
#include <QBuffer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void addWidget();
void delWidget();
private:
Ui::MainWindow *ui;
QVBoxLayout *layout;
QWidget *containWidget;
};
The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓