0
实现从QAbstractListModel一个StringListModel这段代码的目的是显示字符串列表与QtCore.QAbstractListModel
错误而在PyQt的
import sys
from PyQt4 import QtGui, QtCore
class StringListModel(QtCore.QAbstractListModel):
def __init__(self, strings):
QtCore.QAbstractListModel.__init__(self)
self._string_list = strings
def rowCount(self):
return len(self._string_list)
def data(self, index, role):
if not index.isValid() : return QtCore.QVariant()
if role != QtCore.Qt.DisplayRole : return QtCore.QVariant()
if index.row() <= self.rowCount() : return QtCore.QVariant()
return QtCore.QVariant(self._string_list[index.row()])
def headerData(self, section, orientation, role = QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole : return QtCore.QVariant()
if orientation == QtCore.Qt.Horizontal : return QtCore.QVariant("Column %s"%section)
else:
return QtCore.QVariant("Row %s"%section)
if __name__ == '__main__':
a = QtGui.QApplication(sys.argv)
lines = ["item 1", "item 2", "item 3"]
model = StringListModel(lines)
view = QtGui.QListView()
view.setModel(model)
view.setWindowTitle("String list model")
view.show()
a.exec_()
我有错误herited模型是
TypeError: rowCount() takes exactly 1 positional argument (2 given)
谢谢,但现在我有另一个错误:TypeError:PyQt4.QtCore.QVariant表示映射类型,不能实例化。这是QVariant未占用的类型吗? – nam 2012-07-30 13:53:29
看到这个答案http://stackoverflow.com/questions/10382025/qvariant-in-qcombobox-python-2-vs-python-3。值得一提的是有两种使用PyQt4的方式 - 一种是直接使用QVariant,另一种是使用普通的python对象。您似乎设置为使用不直接使用QVariant的较新版本。尝试使用直接的python对象而不是QVariants。 (如果它不起作用,你可能想作为一个新问题发布) – ChrisB 2012-07-30 14:03:00
谢谢,我要试一试! – nam 2012-07-30 14:15:52