Skip to content

[Linux ]在 Ubuntu 18.04 配置 Qt Designer 來開發 Python 的 GUI 介面

在 Python 當中,開發圖形化界面時使用 PyQt5 這個框架可說是再方便不過。從前我也紀錄過在 Windows + PyCharm 底下配置的方法:《PyQt5 基本教學 (1) 安裝 PyQt5,印出 Hello World!》,如果有類似的需求可以參考這篇。


若是想要更加了解何謂 PyQt5,可以參考這裡:https://pypi.org/project/PyQt5/

在 Linux 的系統底下安裝方法其實又更簡單了,以下簡單紀錄一下。

安裝 Qt Designer

在開始之前,我們需要安裝以下套件:

sudo apt-get install qt5-default
sudo apt-get install qttools5-dev-tools
sudo pip3 install pyqt5

安裝好之後,可以使用以下指令打開 Qt Designer:

designer

Output:

我們放置一個 Label 元件在視窗上,然後按下 Ctrl + S 儲存起來,副檔名為 .ui 檔。

當然,這樣還不能夠使用 Python 讀取。來到儲存 UI 檔的路徑底下,使用以下指令轉換(假設我儲存為 UI.ui):

pyuic5 UI.ui -o UI.py

pyuic5 可以將 UI 檔轉換為 py 檔,這樣我們就可以正常讀取了。

另外開新的 Python 檔案:

from PyQt5 import QtWidgets
from UI import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.setText('Hello World!')


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())



Output:

這樣一來就大功告成了!


題外話

如果想要配置在 PyCharm 中直接呼叫 Qt Designer,可以參考我之前寫的這篇《PyQt5 基本教學 (1) 安裝 PyQt5,印出 Hello World!》

designer 以及 pyuic5 的路徑可以使用 whereis 指令找到。

Leave a Reply