2012-07-30 28 views
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)

回答

1

問題是QAbstractItemModel.rowCount採用'父'參數。下面的調整抑制了錯誤(雖然我不知道它實際上實現了正確的邏輯)

def rowCount(self, parent=None): 
    return len(self._string_list) 

另外,你確定QListWidget不提供您需要的功能?

+0

謝謝,但現在我有另一個錯誤:TypeError:PyQt4.QtCore.QVariant表示映射類型,不能實例化。這是QVariant未佔用的類型嗎? – nam 2012-07-30 13:53:29

+0

看到這個答案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

+0

謝謝,我要試一試! – nam 2012-07-30 14:15:52