星期三, 十二月 02, 2015

pyqt 5定制数据模型/Custom data model

目的:qml中combobox的Model用python实现 Model,并通过QML显示出来
要点:qt 5已经改变了roleNames方法,字符串需要用原始ascll 码,字符串前面加b来实现改点;
数据项目必须扩展来自pyqt 5的object.

ListModel.py
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QAbstractListModel, QModelIndex, Qt, QUrl, QVariant
                   
class LottoListModel(QtCore.QAbstractListModel):
    titleRole = Qt.UserRole + 1
    def __init__(self, parent=None):
        super(LottoListModel, self).__init__(parent)

        self.items = []
    def roleNames(self):
        names = {}
        names[self.titleRole] = b"title"
       # names[self.colorRole] = "color"
        return names
         
    def appendRow(self, item):
        self.items.append(item)

    def rowCount(self, parent=QtCore.QModelIndex()):
        print('rowcount.....')
        return len(self.items)

    def data(self, index, role=Qt.DisplayRole):
        print('get data....',index,'   ',role)
        try:
            item = self.items[index.row()]
        except IndexError:
            return QVariant()

        if role == self.titleRole:
            return item.title()


        return QVariant()         

class LottoListItem(object):#核心关键,必须是python object的子类作为项目
    def __init__(self, title):
        self._title = title


    def title(self):
        return self._title

main.py:
import sys
import os
from PyQt5.QtCore import QObject, QUrl, pyqtSlot, QVariant
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QObject, QUrl, Qt,QAbstractTableModel
from PyQt5.QtCore import  pyqtProperty,pyqtSignal
import PyQt5
import ListModel as LM
class MainApp(QObject):
     @pyqtSlot(result=QVariant)
     def getAlgorithm(self):
          self.myModel=LM.LottoListModel()
          self.myModel.appendRow(LM.LottoListItem("0001"))    
          self.myModel.appendRow(LM.LottoListItem("0002"))         
          return self.myModel;

app = QGuiApplication (sys.argv)
engine=QQmlApplicationEngine()
ctx = engine.rootContext()

engine.load(QUrl("view.qml "))
window = engine.rootObjects()[0]
_MainApp = MainApp(window)
_MainApp.logwin[str].connect(window.logger)
_MainApp.getAlgorithm();
ctx.setContextProperty("py_MainApp", _MainApp)

window.show()
sys.exit(app.exec_())

         
view.qml

import QtQuick 2.5
import QtQuick.Controls 1.4
Rectangle {
   id: myItem

     color:'red'
   width: 500; height: 500


ComboBox {
    model:py_MainApp.getAlgorithm()
    width: 200
     }
ListView {
    width: 200; height: 250

    model: myModel
    delegate: Text {title }
     }
}