为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

阿晨1998 2022-05-11 15:52:50
所以我不确定这是一个错误还是什么,但我花了很长时间来解决这个问题,但无法解决。访问调用QObject::property()函数时会出现问题。这是一个最小的可重现示例:import sysfrom PySide2 import QtCorefrom PySide2.QtWidgets import QApplicationfrom PySide2.QtCore import Qt, QCoreApplication, QObject, Slotfrom PySide2.QtQml import QQmlApplicationEngine, QQmlContextclass 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.ageif __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)
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超5个赞

您的代码失败,因为返回的变量getName不是 aQObject而是 a str,类似于getAge返回 a 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


查看完整回答
反对 回复 2022-05-11
  • 1 回答
  • 0 关注
  • 349 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号