QTreeView setModel model.index (2)

本文介绍了一个使用PyQt5实现的简单模型视图架构案例,通过StringListModel类,展示了如何自定义QAbstractListModel子类来处理字符串列表,并在QListView和QTableView中显示。代码示例涵盖了模型的创建、数据角色的处理以及头数据的提供。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

import sys

from PyQt5.QtCore import *

from PyQt5.QtWidgets import *

from PyQt5.QtGui import *


class StringListModel(QAbstractListModel):
    def __init__(self, stringList, parent=None):
        super(StringListModel, self).__init__(parent)
        self.stringList = stringList

    # int rowCount(const QModelIndex &parent = QModelIndex()) const;
    # QVariant data(const QModelIndex &index, int role) const;
    # QVariant headerData(int section, Qt::Orientation orientation,
    #                     int role = Qt::DisplayRole) const;

    def rowCount(self,parent=QModelIndex()):

        return len(self.stringList)

    def data(self,index,role= Qt.DisplayRole):

        if (not index.isValid()):
            return QVariant()

        if (index.row() >= len(self.stringList)):
            return QVariant()

        if (role == Qt.DisplayRole):
            return self.stringList[index.row()]
        else:
            return QVariant()

    def headerData(self, section, orientation, role= Qt.DisplayRole):

        if (role != Qt.DisplayRole):
            return QVariant()
        # print(type(section))
        # print(section)
        if (orientation == Qt.Horizontal):
            return "Column %d" % (section)
        else:
            return "Row %d" % (section)



if __name__ == "__main__":

    app = QApplication(sys.argv)

    qlist = list()
    qlist.append("a")
    qlist.append("b")
    qlist.append("c")
    qlist.append("abcd")

    model = StringListModel(qlist)
    qlistView = QListView()

    qlistView.setModel(model)

    qlistView.show()

    tableView = QTableView()

    tableView.setModel(model)

    tableView.show()

    app.exec_()

效果:
在这里插入图片描述
不可编辑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值