PyQt MCV模型绑定到配置实战

13 篇文章 0 订阅

折腾了一下午,终于大致了解了Qt的数据绑定机制,大致原理就是继承QAbstractTableModel重写了里面的数据处理的方法,大致参考git上的代码。国内很多教程写的都很浅显,没有深入了解数据绑定的思想,更多的是繁琐的赋值。

参考了别人的文章
ItemDataRole包含的Role:

DisplayRole :主要用于以文本的形式显示数据。
EditRole:可用于文本数据的编辑。
DecorationRole:可以将数据通过图标的方式呈现出来。
ToolTipRole :实现当鼠标处于选中的数据时,显示出数据的相关提示。
StatusTipRole :在状态栏显示提示的数据
WhatsThisRole:可以通过选中数据摁下快捷键shift+F1来显示提示。
FontRole :可以改变数据的字体。
TextAlignmentRole :可以将文本的位置进行居中、居左居右调整。
BackgroundColorRole :可以改变背景色。
TextColorRole:设置文字颜色
ForegroundRole:可以改变前景色
CheckStateRole:在某列中设置了CheckStateRole角色后,设置的列则可以显示出一个CheckBox。
AccessibleTextRole:用于辅助功能和插件扩展的文本(如屏幕阅读器)
AccessibleDescriptionRole:用于无障碍项目的描述
SizeHintRole:可以提示相应大小
InitialSortOrderRole:标题视图初始排序顺序
UserRole:用于应用程序的特定目的(自己定义用途).用户自己决定使用什么数据,如何处理数据。

————————————————
版权声明:本文为CSDN博主「LMS_CL」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38516302/article/details/107243292

#!/usr/bin/env python
# encoding: utf-8
"""
Created on 2017年4月21日
@author: weike32
@site: https://pyqt.site ,https://github.com/weike32
@email: 394967319@qq.com
@file: CopyContent
@description: 查阅了很多博客,如果有异,可以联系作者邮箱。本Demo仅作学习参考用,保有后续相关权益。
"""
import json
import sys

import typing
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.uic.properties import QtCore
from PyQt5.QtCore import QAbstractTableModel, QAbstractItemModel


class CustomModel(QAbstractTableModel):

    def __init__(self, data):
        super(CustomModel, self).__init__()
        self._root = data
        self._headers = list(self._root[0].keys())
        self._columncount = len(self._root[0].items())

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

    def columnCount(self, index):
        return self._columncount

    def flags(self, index):
        return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable

    def insertRow(self, row: int, parent: QModelIndex) -> bool:
        self._root.add(self._root[0].copy())
        return True

    def index(self, row, column, parent=None):
        """Override from QAbstractItemModel
        Return index according row, column and parent
        """
        if not self.hasIndex(row, column, parent):
            return QModelIndex()
        return self.createIndex(row, column)

    def data(self, index, role=None):
        """Override from QAbstractItemModel
        Return data from a json item according index and role
        """
        if not index.isValid():
            return None
        if role == Qt.TextAlignmentRole:
            return Qt.AlignCenter
        elif role == Qt.DisplayRole or role == Qt.EditRole:
            return self._root[index.row()][self._headers[index.column()]]

    def setData(self, index: QModelIndex, value: typing.Any, role=Qt.EditRole) -> bool:
        """Override from QAbstractItemModel
        Set json item according index and role
        Args:
            index (QModelIndex)
            value (Any)
            role (Qt.ItemDataRole)
        """
        if role == Qt.EditRole:
            self._root[index.row()][self._headers[index.column()]] = value
            self.dataChanged.emit(index, index)
            return True
        return False

    def headerData(self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole):
        """Override from QAbstractItemModel
        For the JsonModel, it returns only data for columns (orientation = Horizontal)
        """
        if role != Qt.DisplayRole:
            return None

        if orientation == Qt.Horizontal:
            return self._headers[section]


class MyTable(QTableView):
    def __init__(self, parent=None):
        super(MyTable, self).__init__(parent)
        self.setWindowTitle("我是一个表格")
        # self.setWindowIcon(QIcon("male.png"))
        self.datas = []
        # with open('ModelingItemConfig.json') as f:
        #     config=json.load(f)
        #     self.datas = config['Items']
        for i in range(5):
            temp_dict = dict()
            temp_dict['hello'] = False
            temp_dict['今天'] = i
            temp_dict['明天'] = i * 20
            self.datas.append(temp_dict)
        model = CustomModel(self.datas)
        self.setModel(model)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.setAlternatingRowColors(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myTable = MyTable()
    myTable.show()
    myTable.resize(500, 300)
    app.exit(app.exec_())
    print(myTable.datas)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值