简体   繁体   English

没有黑客就无法在PySide2上使用QAbstractListModel子类

[英]Cannot get a QAbstractListModel subclass working on PySide2 without a hack

Using the work-in-progress PySide2 (to be able to use Qt5), I have the following code: 使用进行中的PySide2(能够使用Qt5),我有以下代码:

main.qml: main.qml:

import QtQuick 2.0
import QtQuick.Controls 1.3

ApplicationWindow {
    visible: true
    ListView {
        width: 100
        height: 100
        model: listModel
        delegate: Text {
            text: model.name
        }
    }
}

main.py: main.py:

from sys import argv, exit

from PySide2.QtCore import QAbstractListModel
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine


class TaskListModel(QAbstractListModel):

    _COLUMNS = ('name',)

    def data(self, index, role):
        if role == self._COLUMNS.index('name'):
            return str(index.row())
        return None

    def roleNames(self):
        return dict(enumerate(self._COLUMNS))

    def rowCount(self, parent):
        return 1


app = QGuiApplication(argv)
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty('listModel', None)
engine.load('main.qml')
engine.rootContext().setContextProperty('listModel', TaskListModel())
exit(app.exec_())

The 3 method calls on the engine object towards the end of main.py are the way they are because: main.py末尾调用engine对象的3种方法是因为:

  1. I get Unable to assign [undefined] to QString if I use: 如果使用以下命令Unable to assign [undefined] to QString

     engine.rootContext().setContextProperty('listModel', TaskListModel()) engine.load('main.qml') 
  2. I get ReferenceError: listModel is not defined if I use: 我收到ReferenceError: listModel is not defined如果使用以下方法, ReferenceError: listModel is not defined

     engine.load('main.qml') engine.rootContext().setContextProperty('listModel', TaskListModel()) 

Is my way the only way to do this properly? 我的方法是正确执行此操作的唯一方法吗? Shouldn't the code in my first bullet above work as well? 我上面第一个项目符号中的代码也不能正常工作吗?

It seems that PySide2 removes TaskListModel() from memory if you assign it to some variable, I have found 2 solutions: 似乎PySide2TaskListModel()分配给某个变量,则会从内存中删除它,我发现了2个解决方案:

  • Create a variable that stores the model: 创建一个存储模型的变量:

app = QGuiApplication(argv)
engine = QQmlApplicationEngine()
model = TaskListModel()
engine.rootContext().setContextProperty('listModel', model)
engine.load('main.qml')
exit(app.exec_())
  • Pass a parent to the model: 将父级传递给模型:

app = QGuiApplication(argv)
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty('listModel', TaskListModel(engine))
engine.load('main.qml')
exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM