QT QListWidget删除item和插入widget

时间:2021-02-26 19:36:28
main.cpp
#include <QApplication>#include <QDialog>#include <QLabel>#include <QTextCodec>#include "demo.h"int main(int argc, char* argv[]){    QApplication a(argc,argv);    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());    demo *w = new demo;    w->show();    return a.exec();}

demo.cpp

#include "demo.h"

demo::demo(QWidget *parent) :
QDialog(parent)
{

//添加Item
QStringList strList;
strList<<"Item1"<<"Item2"<<"Item3"<<"Item4"<<"Item5";
listWidget = new QListWidget;
listWidget->addItems(strList); //向QListWidget中添加items

//在QListWidget中添加按钮
QWidget *widget = new QWidget;
QHBoxLayout *listWidgetlayout = new QHBoxLayout(widget);
QLabel *label = new QLabel(tr("放入QListWidget中"));
QPushButton *btn = new QPushButton(tr("QListWidget中的按钮"));
listWidgetlayout->addWidget(label);
listWidgetlayout->addWidget(btn);
widget->setLayout(listWidgetlayout);
QListWidgetItem *listitem = new QListWidgetItem;
listWidget->addItem(listitem);
listWidget->setItemWidget(listitem, widget);
listitem->setSizeHint(QSize(0, 40));
widget->show();

//清空和删除按钮
deletebtn = new QPushButton(tr("删除"));
clearbtn = new QPushButton(tr("清空"));
QHBoxLayout *btnlayout = new QHBoxLayout;
btnlayout->addStretch(1);
btnlayout->addWidget(deletebtn);
btnlayout->addStretch(1);
btnlayout->addWidget(clearbtn);
btnlayout->addStretch(1);

QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(listWidget);
layout->addLayout(btnlayout);
setLayout(layout);

connect(listWidget, SIGNAL(itemSelectionChanged()), this, SLOT(items())); //选中的item发生变化时执行items()
connect(deletebtn, SIGNAL(clicked(bool)), this, SLOT(deleteitem()));
connect(clearbtn, SIGNAL(clicked(bool)), this, SLOT(clearListWidget()));
}

demo::~demo()
{

}

void demo::deleteitem()
{
if(0 == listWidget->count()) //获取items数量,当QListWidget中没有item时返回
return;
itemlist = listWidget->currentItem();
str = itemlist->text(); //获取当前选中item字符串
int i=0;
itemlist1 = listWidget->item(i);
str1 = itemlist1->text(); //获取索引为0的item字符串
while(str1 != "") //删除选中的item
{
itemlist1 = listWidget->item(i);
str1= itemlist1->text();
if(str == str1)
{
listWidget->removeItemWidget(itemlist1);
delete itemlist1;
return;
}
++i;
}
}

void demo::clearListWidget()
{
listWidget->clear(); //清空items
}

void demo::items()
{
qDebug()<<"items()";
}
demo.h

#ifndef DEMO_H
#define DEMO_H

#include <QListWidget>
#include <QLayout>
#include <QDialog>
#include <QPushButton>
#include <QDebug>
#include <QLabel>

class demo : public QDialog
{
Q_OBJECT

public:
explicit demo(QWidget *parent = 0);
~demo();

public slots:
void deleteitem();
void items();
void clearListWidget();

private:
QString str;
QString str1;
QListWidgetItem *itemlist;
QListWidgetItem *itemlist1;
QPushButton *deletebtn;
QPushButton *clearbtn;
QListWidget *listWidget;

};

#endif // DEMO_H


运行结果图:
QT QListWidget删除item和插入widget