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

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


# 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>

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


元芳怎么了
浏览 130回答 0
0回答

MM们

我找到了原始问题的解决方法,因为自动生成的代码似乎无法按预期工作。这个答案提供了一种在 PySide 中模仿 PyQt 模块功能的方法uic。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python