PyQt5 TableModel(QAbstractTableModel)没有显示数据

时间:2019-02-12 16:11:09

标签: python pyqt5 qabstracttablemodel

您好,我最近开始使用PyQt5并尝试实现csv解析器:

但是我在QAbstractTableModel的后代中苦苦挣扎。 视图中没有数据!

qt5(https://doc.qt.io/qt-5/qabstracttablemodel.html)的教程说我必须在TableModel类中实现一些方法。 我想我做到了,但是-视图中没有数据。

from PyQt5.QtWidgets import \
    QApplication, QWidget, QVBoxLayout, QTableView
from PyQt5.QtCore import \
    QAbstractTableModel, QVariant, Qt


class TableModel(QAbstractTableModel):
    def __init__(self):
        super().__init__()
        self._data = []

    def set(self, data):
        self._data = data

    def rowCount(self, index):
        return len(self._data)

    def columnCount(self, index):
        return len(self._data[0])

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()
        elif role == Qt.DisplayRole:
            row = index.row()
            return self._data[row]
        else:
            return QVariant()

    def headerData(self, p_int, Qt_Orientation, role=None):
        return self._data[0]


class View(QWidget):
    def __init__(self):
        super().__init__()

        model = TableModel()
        model.set(data)

        self.tbl = QTableView(self)
        self.tbl.setModel(model)

    def setup(self):
        self.setMinimumHeight(600)
        self.setMinimumWidth(800)

        self.vlayout = QVBoxLayout(self)
        self.vlayout.addWidget(self.tbl)


def main():
    import sys
    app = QApplication(sys.argv)

    window = View()
    window.setup()
    window.show()

    sys.exit(app.exec_())

main()

一些来自这里的模拟数据:

data = [f.strip().split(",") for f in """\
    id,first_name,last_name,email,gender,ip_address
    1,Hillard,Tasseler,htasseler0@google.com.br,Male,104.153.237.243
    2,Tyrus,Oley,toley1@ft.com,Male,163.73.24.45
    3,Kora,Covil,kcovil2@privacy.gov.au,Female,158.44.166.87
    4,Phineas,McEntee,pmcentee3@rambler.ru,Male,71.82.246.45
    5,Dottie,Spraging,dspraging4@berkeley.edu,Female,226.138.241.22
    6,Andria,Ivatts,aivatts5@about.com,Female,57.5.76.78
    7,Missy,Featherstone,mfeatherstone6@unblog.fr,Female,9.56.215.203
    8,Anstice,Sargant,asargant7@about.me,Female,36.115.185.109
    9,Teresita,Trounce,ttrounce8@myspace.com,Female,240.228.133.166
    10,Sib,Thomke,sthomke9@ibm.com,Female,129.191.2.7
    11,Amery,Dallander,adallandera@elpais.com,Male,4.115.194.100
    12,Rourke,Rowswell,rrowswellb@bloomberg.com,Male,48.111.190.66
    13,Cloe,Benns,cbennsc@slideshare.net,Female,142.48.24.44
    14,Enos,Fery,eferyd@pen.io,Male,59.19.200.235
    15,Russell,Capelen,rcapelene@fc2.com,Male,38.205.20.141""".split()]

1 个答案:

答案 0 :(得分:2)

数据方法必须以字符串而不是列表的形式返回值,在您的情况下,self._data[row]是列表,因此解决方案是使用列从该列表中获取单个元素:

def data(self, index, role=Qt.DisplayRole):
    if not index.isValid():
        return QVariant()
    elif role == Qt.DisplayRole:
        row = index.row()
        col = index.column()
        return self._data[row][col]
    else:
        return QVariant()