PySide2(Qt for Python)如何在 QMainWindow 子类中加载 .ui 文件

PySide2 (Qt for Python) how to load a .ui file in a QMainWindow subclass

我正在尝试使用 Qt Creator 和 Qt for Python 为新应用程序创建快速原型。但是,向导生成的代码对我来说意义不大。这是 Qt Creator 生成的 main.py 文件:

# This Python file uses the following encoding: utf-8
import sys
import os


from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader


class MyMainWindow(QMainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.load_ui()

    def load_ui(self):
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        loader.load(ui_file, self)
        ui_file.close()

if __name__ == "__main__":
    app = QApplication([])
    widget = MyMainWindow()
    widget.show()
    sys.exit(app.exec_())

这是一个简单的 form.ui,只有一个按钮:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MyMainWindow</class>
 <widget class="QMainWindow" name="MyMainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MyMainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QPushButton" name="pushButton">
      <property name="text">
       <string>PushButton</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

我只是不明白 MyMainWindow class 中的 load_ui 函数的用途。我知道 PyQt5 可以在使用 uic 模块初始化小部件期间加载 .ui 文件。据我所知,这对于 Python 的 Qt 是不可能的。我错过了什么吗?我正在使用 Qt Creator 4.13。

我找到了解决原始问题的方法,因为自动生成的代码似乎没有按预期工作。 This answer 提供了一种在 PySide 中模仿 PyQt uic 模块功能的方法。