我正在创建一个支持搜索的项目列表,我想知道哪种方法对我来说最好的方法是保持左侧图标的支持,同时在每个项目的最右侧插入一个复选框在列表中?我知道默认列表视图不支持右侧的复选框,只支持左侧的复选框,我不希望这样做。
应该使用QListView来工作,还是应该使用QTableView或QTableWidget或类似的东西?
我正在尝试这样做:
代码:
import os, sys
from PySide import QtGui, QtCore
class Dialog(QtGui.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent=parent)
# controls
self.lineEdit = QtGui.QLineEdit(self)
self.list = QtGui.QListView(self)
self.list.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
model = QtGui.QSortFilterProxyModel()
model.setSortCaseSensitivity(QtCore.Qt.CaseSensitivity.CaseInsensitive)
model.setSourceModel(QtGui.QStandardItemModel())
model.setDynamicSortFilter(False)
self.list.setModel(model)
self.createModel()
# layout
vLayout = QtGui.QVBoxLayout(self)
vLayout.addWidget(self.lineEdit)
vLayout.addWidget(self.list)
# signals/slots
self.lineEdit.textChanged.connect(self.filterItems)
def createModel(self):
codes = {
'Zebra': QtCore.Qt.black,
'Tiger': QtCore.Qt.yellow,
'Gorilla': QtCore.Qt.gray,
'Horse': QtCore.Qt.green,
'Lion': QtCore.Qt.red
}
for k, v in codes.items():
px = QtGui.QPixmap(12,12)
px.fill(v)
item = QtGui.QStandardItem(QtGui.QIcon(px), k)
item.setCheckable(True)
self.list.model().sourceModel().appendRow(item)
self.list.model().sourceModel().sort(0, QtCore.Qt.AscendingOrder)
def filterItems(self):
filter_text = str(self.lineEdit.text()).lower()
for row in range(self.list.model().rowCount()):
if filter_text in str(self.list.model().item(row).text()).lower():
self.list.setRowHidden(row, False)
else:
self.list.setRowHidden(row, True)
def main():
app = QtGui.QApplication(sys.argv)
ex = Dialog()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()