python - PySide2 在访问 QObject::property() 时崩溃

标签 python qt pyside2 qobject qmetaobject

所以我不确定这是一个错误还是什么,但我花了很长时间来弄清楚这一点,但无法解决。访问调用 QObject::property() 函数时会出现问题。 这是一个最小的可重现示例:

import sys

from PySide2 import QtCore
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import Qt, QCoreApplication, QObject, Slot
from PySide2.QtQml import QQmlApplicationEngine, QQmlContext



class MyItem(QObject):
    def __init__(self):
        super(MyItem, self).__init__()
        self.name = "John"
        self.age = 22

    @QtCore.Property(QtCore.QObject, constant=True)
    def getName(self):
        return self.name

    @QtCore.Property(QtCore.QObject, constant=True)
    def getAge(self):
        return self.age

if __name__ == '__main__':
    app = QApplication(sys.argv)
    provider = MyModelProvider()
    item = MyItem()
    print(item.property("getName")) # the program crashes here
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty('provider', provider)
    engine.load('qml/main.qml')
    sys.exit(app.exec_())

程序总是崩溃并显示以下输出:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

最佳答案

您的代码失败,因为返回 getName 的变量不是 QObject 而是 str,类似于 getAge > 返回一个int,所以解决方案是设置正确的签名

import sys

from PySide2.QtCore import Property, QObject, QCoreApplication


class MyItem(QObject):
    def __init__(self, parent=None):
        super(MyItem, self).__init__(parent)
        self.name = "John"
        self.age = 22

    @Property(str, constant=True)
    def getName(self):
        return self.name

    @Property(int, constant=True)
    def getAge(self):
        return self.age


if __name__ == "__main__":
    app = QCoreApplication(sys.argv)
    item = MyItem()
    print(item.property("getName"))
    print(item.property("getAge"))

输出:

John
22

关于python - PySide2 在访问 QObject::property() 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664401/

相关文章:

python - 在 Python 中修复损坏的 HTML - Beautifulsoup 不工作

python - 根据来自其他两个 DataFrame 的索引合并两个 DataFrame

Python:将矩阵转换为半正定

python - 无法连接到从 Python 发出的 QML 中的信号

python - 我可以使用 eventFilter 来忽略小部件的事件吗

python - 我需要找到两组横滚角和偏航角之间的角度

c++ - 从命令行编译一个 Qt 项目

c++ - 将内存分配给类的指针

c++ - Qt QSplitter 窗口调整大小的固定高度小部件

python - Python 列表更新时更新 ListView