QListWidget

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <QApplication>
#include <QWidget>
#include <QListWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QMessageBox>

void setupListWidgetDemo(QWidget *parent) {
QVBoxLayout *mainLayout = new QVBoxLayout(parent);

// --- 1. 创建列表控件 ---
QListWidget *listWidget = new QListWidget(parent);

// 添加简单的文字项
listWidget->addItem("C++ 基础教程");
listWidget->addItem("Qt 控件指南");

// 添加带图标的项(使用 QListWidgetItem 可以设置更多细节)
QListWidgetItem *itemWithIcon = new QListWidgetItem(
parent->style()->standardIcon(QStyle::SP_ComputerIcon), "我的电脑"
);
listWidget->addItem(itemWithIcon);

// 允许按住 Ctrl 进行多选
listWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

// --- 2. 交互按钮 ---
QHBoxLayout *btnLayout = new QHBoxLayout();
QPushButton *btnAdd = new QPushButton("添加新项");
QPushButton *btnDel = new QPushButton("删除选中");
btnLayout->addWidget(btnAdd);
btnLayout->addWidget(btnDel);

// --- 3. 信号处理:双击某一项 ---
QObject::connect(listWidget, &QListWidget::itemDoubleClicked, [](QListWidgetItem *item) {
QMessageBox::information(nullptr, "提示", "你双击了:" + item->text());
});

// --- 4. 逻辑:动态添加 ---
QObject::connect(btnAdd, &QPushButton::clicked, [listWidget]() {
static int count = 1;
listWidget->addItem(QString("新任务 %1").arg(count++));
});

// --- 5. 逻辑:删除选中 ---
QObject::connect(btnDel, &QPushButton::clicked, [listWidget]() {
// 获取所有选中的项(因为开启了多选)
QList<QListWidgetItem*> items = listWidget->selectedItems();
for (QListWidgetItem* item : items) {
delete listWidget->takeItem(listWidget->row(item));
}
});

mainLayout->addWidget(new QLabel("任务清单(双击查看详情):"));
mainLayout->addWidget(listWidget);
mainLayout->addLayout(btnLayout);
}

int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWidget w;
w.setWindowTitle("QListWidget 列表演示");
w.resize(300, 400);
setupListWidgetDemo(&w);
w.show();
return a.exec();
}