我终于找到了解决方案:
我将消息存储为一个将变量名称与信息相关联的字典(隐藏状态的布尔值、消息标签字符串、排序顺序信息):
self.aMessages = {"bMessage1": [False, "This is the message 1", 0],
"bMessage2": [False, "This is the message 2", 0],
"bMessage3": [False, "This is the message 3", 0],
"bMessage4": [False, "This is the message 4", 0],
"bMessage5": [False, "This is the message 5", 0]}
模型基于QStandardItemModel
:
class MessageListModel(QtGui.QStandardItemModel):
def __init__(self, parent=None, *args):
QtGui.QStandardItemModel.__init__(self, parent, *args)
def data(self, index, role):
if not index.isValid():
return QtCore.QVariant()
elif role != QtCore.Qt.DisplayRole:
if role == QtCore.Qt.BackgroundRole:
status = index.data(QtCore.Qt.UserRole)
if status == True:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
elif status == False:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.red))
return QtGui.QStandardItemModel.data(self, index, role)
def addItem(self, label, value):
item = QtGui.QStandardItem(label)
item.setEditable(False)
item.setData(value, QtCore.Qt.UserRole)
item.setData(0, QtCore.Qt.UserRole + 1)
item.setDropEnabled(False)
self.appendRow(item)
然后,模型填充:
tm = MessageListModel()
for msg in self.aMessages.itervalues():
tm.addItem(msg[1], msg[0])
ListView.setModel(tm)
和一个更新模型的线程:
class MessagesUpdateThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
self.exiting = False
def __del__(self):
self.exiting = True
self.wait()
def run(self):
while not self.exiting:
self.emit(QtCore.SIGNAL("updateMessages()"))
self.sleep(1)
以及用于更新和排序模型的插槽:
def updateMessages(self):
MsgList = self.aMessages.values()
model = self.ui.Messages.model()
for i in xrange(len(MsgList)):
value = MsgList[i][0]
index = model.index(i, 0)
model.setData(index, MsgList[i][1])
model.setData(index, value, QtCore.Qt.UserRole)
model.setData(index, MsgList[i][2], QtCore.Qt.UserRole + 1)
self.ui.Messages.setRowHidden(i, not value)
del MsgList
model.setSortRole(QtCore.Qt.UserRole + 1)
model.sort(0)
然后将插槽连接到线程信号:
self.m = MessagesUpdateThread()
QtCore.QObject.connect(self.m, QtCore.SIGNAL("updateMessages()"), self.updateMessages)
self.m.start()