Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a data structure using NamedTuple (I could switch to dataclass if it's preferable!) to contain a PyQt5 QWidget. I need to set the type of the widget but also would like to set a default.

When I check type(PyQt5.QtGui.QLabel()) it returns <class 'PyQt5.QtWidgets.QLabel'>

Trying

from typing import NamedTuple
import PyQt5

class myStat(NamedTuple):
     name:str
     value:float=0.0
     qlabel:PyQt5.QWidgets.QLabel=PyQt5.QtGui.QLabel()

I cannot import it to my actual application with from myFile import myStat I get the error `QWidget: Must construct a QApplication before a QWidget.

Any advice on how to do this? Inside my application I'm trying to do

x=myStat(name='foo',value=5.0)

but it's evidently not even getting there since it's failing on import.

question from:https://stackoverflow.com/questions/65623132/namedtuple-or-dataclass-containing-default-pyqt5-qwidget

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
154 views
Welcome To Ask or Share your Answers For Others

1 Answer

The error is caused because the object is created when the class is declared but at that time the QApplication has not been created, a possible solution is to use default_factory in a dataclass, but anyway when you create the object it must have already created a QApplication :

import sys
from dataclasses import dataclass, field

from PyQt5.QtWidgets import QApplication, QLabel


@dataclass
class MyStat:
    name: str
    value: float = 0.0
    qlabel: QLabel = field(default_factory=QLabel)


def main():
    app = QApplication(sys.argv)

    x = MyStat(name="foo", value=5.0)
    print(x.qlabel)
    x.qlabel.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...