PyQt5 加载UI文件

PyQt5直接加载UI文件,而不是将其转化为.py文件。

PySide2直接加载UI文件

通过Qt Creator新建Qt for Python项目

自动生成直接加载UI文件代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys

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


class UITest(QWidget):
def __init__(self):
super(UITest, self).__init__()
self.load_ui()

def load_ui(self):
loader = QUiLoader()
path = os.fspath(Path(__file__).resolve().parent / "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 = UITest()
widget.show()
sys.exit(app.exec_())

PyQt5直接加载UI文件

仿造上述代码

```python

This Python file uses the following encoding: utf-8

import sys

from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.uic import loadUi

class UITest(QWidget):
def init(self, parent=None):
super().init()
loadUi(‘form.ui’, self)
self.setFixedSize(600, 400)
self.pushButton.clicked.connect(self.onButtonClicked)#可直接self.pushButton,该QPushButton变量在UI中定义

def onButtonClicked(self):
    x = random.randint(self.pushButton.width(), self.width() - self.pushButton.width())
    y = random.randint(self.pushButton.height(), self.height() - self.pushButton.height())
    self.pushButton.move(x, y)

if name == “main“:
app = QApplication([])
widget = UITest()
widget.show()
sys.exit(app.exec_())

项目

参见项目示例
github
gitee


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!