QListWidget记录汇总。
当允许编辑时,编辑后失去焦点可触发该信号,假设槽函数为onItemChanged
,如果此时选中其他行,此时的currentRow()
不是被编辑的row
1 2 3 4 5
| void Test::onItemChanged(QListWidgetItem * _item) { auto row = listWidget->currentRow(); auto row2 = listWidget->row(_item); }
|
2. 增加行
1
| auto listWidgetItem = new QListWidgetItem("test", listWidget);
|
可编辑、可选中
1
| listWidgetItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable);
|
增加一行会触发QListWidget::itemChanged(QListWidgetItem * _item)
信号,不想触发可以关闭
1 2 3 4
| disconnect(listWidget, &QListWidget::itemChanged, this, &Test::onItemChanged); auto listWidgetItem = new QListWidgetItem("test", listWidget); listWidgetItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable); connect(listWidget, &QListWidget::itemChanged, this, &Test::onItemChanged);
|
3. 删除行
1 2
| auto item = listWidget->takeItem(index); delete item;
|
4. 去掉item选中的虚线框
1
| listWidget->setFocusPolicy(Qt::NoFocus);
|
或
1 2 3
| QListWidget{ outline:0px; }
|
5. item颜色交替
1
| listWidget->setAlternatingRowColors(true);
|
1 2 3 4
| QListWidget { background:gray; alternate-background-color: black; }
|

算上背景色有两种颜色
或
1 2 3 4 5 6 7 8 9 10 11 12 13
| QListWidget { background:gray; }
QListWidget::item:alternate { background:pink; }
QListWidget::item:!alternate { background:black; }
|

算上背景色有三种颜色
6. 编辑框
同QLineEdit
1 2 3 4 5 6
| QListWidget QLineEdit { background: gray; color:white; border:none; }
|
7. 部分样式
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
| QListWidget { border: none; background:gray; color: green; }
QListWidget{ outline:0px; }
QListWidget QLineEdit { background: gray; color:white; border:none; }
QListWidget::item:alternate { background:pink; }
QListWidget::item:!alternate { background:black; }
QListWidget::item{ color: yellow; border-bottom: 1px solid blue; }
QListWidget::item:hover { background: red; color: white; }
QListWidget::item:selected { background: red; color:white; }
|
效果如下:
