如何使选中的 QListView 项可见?

How do you make the selected QListView item visible?

我是 Python 的新手。我有一个带有 2 个 PyQt5 Qlistviews (LV) 的 Python 表单。有一个可用的和一个选定的列表视图。我可以加载可用的 LV 并查看它的内容。我可以检查要移动到所选 LV 的项目,按下按钮,项目移动,但它的文本在所选 LV 中不可见。

def Add_Button_click(self):
    # Add the available item to the selected box.
    self.sel_model = QStandardItemModel(self.Selected_List)
    # Loop through the available model finding items that have been checked.

    for index in range(self.avail_model.rowCount()):
        item = self.avail_model.item(index)
        # Add the item to the selected model
        if item.checkState() == QtCore.Qt.Checked:
            self.sel_model.appendRow(item)
    self.Selected_List.setModel(self.sel_model)

一个QStandardItem不能属于2个模型,所以如果你想移动它必须先用takeRow()移除它,然后再插入到新的模型中。直接做会带来问题,因为要删除的行会改变rowCount(),最好反过来做。

import sys

from PyQt5 import QtWidgets, QtGui, QtCore

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        lay = QtWidgets.QHBoxLayout(self)
        avail_modelLV = QtWidgets.QListView()
        sel_modelLV = QtWidgets.QListView()
        button = QtWidgets.QPushButton("Select")
        lay.addWidget(avail_modelLV)
        lay.addWidget(button)
        lay.addWidget(sel_modelLV)

        button.clicked.connect(self.on_clicked)

        self.avail_model = QtGui.QStandardItemModel()
        self.sel_model = QtGui.QStandardItemModel()

        avail_modelLV.setModel(self.avail_model)
        sel_modelLV.setModel(self.sel_model)
        for text in ["text1", "text2", "text3", "text4"]:
            it = QtGui.QStandardItem(text)
            it.setCheckable(True)
            self.avail_model.appendRow(it)

    def on_clicked(self):
        self.sel_model.clear()
        for row in reversed(range(self.avail_model.rowCount())):
            it = self.avail_model.item(row)
            if it.checkState() == QtCore.Qt.Checked:
                it = self.avail_model.takeRow(row)
                self.sel_model.insertRow(0, it)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())