我想按选中的对象对ListView模型进行排序。在下面的示例中,我尝试添加一个self.model.sort()
,但它似乎没有任何作用,除了Qt.AscendingOrder (最近向我透露了此内容)。
documentation说:“您可以使用findItems()搜索模型中的项目,然后通过调用sort()来对模型进行排序”,但实际上只有self.model.sort(QtCore.Qt.DescendingOrder)
才有效。
我误会了吗?
下面的GUI设置为在设置的时间后启动print_checked_items()
中的任何代码。
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QWizardPage, QListView
class AppRemovalPage(QWizardPage):
def __init__( self, parent ):
super(AppRemovalPage, self).__init__(parent)
self.list_view = QListView(self)
self.model = QtGui.QStandardItemModel(self.list_view)
for line in ('a', 'b', 'c', 'd', 'e'):
self.item = QtGui.QStandardItem(line)
self.item.setCheckable(True)
self.item.setCheckState(QtCore.Qt.Unchecked)
self.model.appendRow(self.item)
self.list_view.setModel(self.model)
self.list_view.clicked.connect(self.getSelectedListItem)
self.list_view.show()
def print_checked_items(self):
self.model.sort(QtCore.Qt.AscendingOrder) # has no effect
for index in range(self.model.rowCount()):
item = self.model.item(index)
if item.checkState() == QtCore.Qt.Checked:
print(item.text(), "was checked")
print("rerun timed script to list checked objects again")
def getSelectedListItem(self):
currentSelection = self.list_view.selectedIndexes()
name = None
row = None
index = None
# Set name for currently selected object in listview
for obj_index in currentSelection:
item = self.model.itemFromIndex(obj_index)
row = item.row()
index = self.model.index(row, 0)
name = self.model.data(index)
self.currName = name
self.currRow = row
self.currIndx = index
app = QApplication([])
listview = AppRemovalPage(None)
listview.show()
QTimer.singleShot(4000, listview.print_checked_items)
app.exec_()