Issue
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.
Solution
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()
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.