Qt 使用可以用 QtDesigner 創(chuàng)建 .ui 文件,并在 QtCreator 中自動(dòng)生成C++文件,從C++中調(diào)用;PyQt 也可以,需要借助 PyQt 提供的 pyuic5 腳本。
工具準(zhǔn)本
- QtDesigner
pip3 install PyQt5-tools - 安裝 PyQt5,包含 pyuic 模塊
pip3 install PyQt5
正確的步驟
- 創(chuàng)建 .ui 文件
打開 QtDesigner,新建,創(chuàng)建一個(gè)簡(jiǎn)單的界面文件,保存為 foo.ui

image.png

image.png
- 轉(zhuǎn)換 .ui 文件為 py 文件
pyuic5 foo.ui -o ui_foo.py
- 使用生成的文件
新建一個(gè) python 源碼文件, bar.py
- 第一種方法: 組合ui
from PyQt5.QtWidgets import QDialog
from ui_foo import Ui_MainWindow
class MainWindow(QDialog):
def __init__(self):
super(MainWindow, self).__init__()
# Set up the user interface from Designer.
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Make some local modifications.
self.ui.colorDepthCombo.addItem("2 colors (1 bit per pixel)")
# Connect up the buttons.
self.ui.okButton.clicked.connect(self.accept)
self.ui.cancelButton.clicked.connect(self.reject)
- 第二種方法: 多繼承
from PyQt5.QtGui import QDialog
from ui_foo import Ui_MainWindow
class MainWindow(QDialog, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# Set up the user interface from Designer.
self.setupUi(self)
# Make some local modifications.
self.colorDepthCombo.addItem("2 colors (1 bit per pixel)")
# Connect up the buttons.
self.okButton.clicked.connect(self.accept)
self.cancelButton.clicked.connect(self.reject)
結(jié)合 pycharm
pycharm 支持 ”external tool" 可以添加自定義的命令到 pycharm 菜單;利用這個(gè),把 pyuic 添加進(jìn)來,提高效率
settings->tools->external tools

image.png
資源文件 qrc
- 用 QtCreator 或 QtDesigner 編輯 qrc

QtCreator 編輯 qrc
前綴 是 qrc 中用來分組的一個(gè)層級(jí),在源碼中體現(xiàn)為路徑
在前綴下 添加文件:圖片等
語(yǔ)言 是由于國(guó)際化的一個(gè)后綴(不同語(yǔ)言自動(dòng)識(shí)別使用資源)
PyQt5 提供工具把 qrc 及其關(guān)聯(lián)的文件編譯為一個(gè) py 文本,只需要引用這個(gè)文本,就可以使用資源。
pyrcc5.exe image.qrc -o rc_image.py使用編譯后的模塊
資源路徑格式 ":前綴/文件名" 或 ":前綴/別名"

資源文件和別名
from rc_image import *
img = QPixmap(":/img/glyphicons-281-settings.png") # 從編譯后的資源文件中導(dǎo)入(文件名)
img = QPixmap(":/img/settings") # 從編譯后的資源文件中導(dǎo)入(別名)