widget.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include
#include
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class TextItemWidget : public QWidget
{
Q_OBJECT
public:
TextItemWidget(QWidget* parent = nullptr);
QString getText() const;
void setText(const QString &value);
signals:
void deleteBtnClicked();
private:
QLabel* label;
QPushButton* btn;
};
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void addItem();
private slots:
void onBtnClicked();
private:
Ui::Widget ui;
QMap<QObject, QListWidgetItem*> widgetItemMap;
};
#endif // WIDGET_H
//widget.cpp文件
#include “widget.h”
#include “ui_widget.h”
#include
#include
#include
const QString str = QStringLiteral(“hello world”);
TextItemWidget::TextItemWidget(QWidget *parent)
: QWidget(parent)
{
label = new QLabel();
btn = new QPushButton(“X”);
btn->setFixedSize(12, 12);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(label);
layout->addWidget(btn);
connect(btn, &QPushButton::clicked, this, &TextItemWidget::deleteBtnClicked);
}
QString TextItemWidget::getText() const
{
return label->text();
}
void TextItemWidget::setText(const QString &value)
{
label->setText(value);
}
-
Widget::Widget(QWidget *parent)
-
QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->pushButton,&QPushButton::clicked,this,&Widget::addItem);
}
Widget::~Widget()
{
delete ui;
}
void Widget::addItem()
{
TextItemWidget* widget = new TextItemWidget();
widget->setText(str);
connect(widget,SIGNAL(deleteBtnClicked()),this,SLOT(onBtnClicked()));
QListWidgetItem* item = new QListWidgetItem();
ui->widget->addItem(item);
ui->widget->setItemWidget(item, widget); // 必须先addItem,后才能setItemWidget
item->setSizeHint(widget->size());
widgetItemMap[widget] = item;
}
void Widget::onBtnClicked()
{
qInfo()<<“zhi xing shan chu”;
QObject* widget = sender();
QListWidgetItem* item = widgetItemMap[widget];
delete item;
// delete widget;
// widgetItemMap.remove(widget);
}