0

Both of the following codes are codes that show empty gui. But the code above is QMainWindow From PyQt5.QtWidgets import QApplication, QMainWindow Use this and the code below is uic.loadUiType. If you look on the Internet, you can't see the difference between the two codes, some using the above and some using the below code. I ask you to explain about this.

#---------------------------upside code------------------------#
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic

[form_class,QMainWindow]=uic.loadUiType('uifile.ui')

class Main(form_class,QMainWindow):

    def __init__(self):
        super().__init__()
        self.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    app.exec()


#---------------------------downside code------------------------#
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic

form_class=uic.loadUiType('uifile.ui')[0]

class Main(form_class,QMainWindow):

    def __init__(self):
        super().__init__()
        self.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    app.exec()
agile
  • 77
  • 5
  • The first is a bad example, as it *overwrites* `QMainWindow` globally, which could be easily mistaken in case the ui was created using a different widget type (such as QDialog). While not technically "wrong", it shouldn't be done. That said, start by reading the [documentation](https://www.riverbankcomputing.com/static/Docs/PyQt5/api/uic/uic-module.html#loadUiType). – musicamante Aug 17 '22 at 08:51
  • My original intention is to ask a question without ```QMainWindow``` importing. I'm sorry to confuse you. I just deleted it. – agile Aug 17 '22 at 09:13
  • That problem was in fact the specific reason for which you shouldn't create `QMainWindow` from that function: conceptually there is absolutely no difference, **assuming** that the ui actually uses a QMainWindow. As said above, doing that can create confusion, and another name should be preferred instead. If you print the result if `loadUiType` you'll see that the second value is still QMainWindow (as explained in the docs, and that's why in the second code it's ignored), so there's absolutely no difference in using that or the imported class, it's just a matter of preference. – musicamante Aug 17 '22 at 09:38
  • The whole point of returning both the *form class* and the *base class* is so that you don't need to know the specific types defined in qt-designer. A more robust usage would therefore be `class Main(*uic.loadUiType('uifile.ui')):`. – ekhumoro Aug 17 '22 at 12:08

0 Answers0