繁体   English   中英

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类中load_ui函数的MyMainWindow 我知道 PyQt5 可以在使用uic模块初始化小部件期间加载.ui文件。 据我所知,这对于 Python 的 Qt 是不可能的。 我错过了什么吗? 我正在使用 Qt Creator 4.13。

我找到了解决原始问题的方法,因为自动生成的代码似乎无法正常工作。 这个答案提供了一种在 PySide 中模拟 PyQt uic模块功能的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM