广告

本站里的文章大部分经过自行整理与测试

2017年5月29日星期一

PyQt5 - GUI 制作

1) 安装

1.1) Python 3.5 + PyQt5

平台用 Ubuntu 16.04, 预设已安装了 Python 2.7 和 Python 3.5

https://www.riverbankcomputing.com/software/pyqt/download5

$ sudo apt-get install python3-pip
$ pip3 install --upgrade pip
$ pip3 install PyQt5

1.2) Qt Creator

# Qt Online Installer for Linux 64-bit (31 MB)
$ wget http://download.qt.io/official_releases/online_installers/qt-unified-linux-x64-online.run
$ chmod +x qt-unified-linux-x64-online.run
$ ./qt-unified-linux-x64-online.run

1.3) IDE

1.3.1) PyCharm

https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=linux&code=PCC
http://jasonmun.blogspot.my/2017/04/ubuntu-ubuntu-make.html

1.3.2) Eclipse + PyDev

http://jasonmun.blogspot.my/2016/04/eclipse-pydev.html

2) 代码编写

https://github.com/shantnu/PyQt_first

2.1) 先用 Qt Creator 制作要用的 GUI 界面 (tax_calc.ui)

Qt Creator - File - New File or Project...
- Files and Classes - Qt - Qt Designer Form
- Choose - Form Template: Main Window - Next - Location: tax_calc.ui

其实 ui 文件也就是一个 xml
https://raw.githubusercontent.com/shantnu/PyQt_first/master/tax_calc.ui

要自己学习重制作界面 tax_calc.ui, 可以看以下
http://pythonforengineers.com/your-first-gui-app-with-python-and-pyqt/

2.2) Python 代码 (以上代码是用 PyQt4, 而以下已改为 PyQt5)

import sys
from PyQt5 import QtWidgets, uic

qtCreatorFile = "tax_calc.ui"

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)


class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.calc_tax_button.clicked.connect(self.CalculateTax)

    def CalculateTax(self):
        price = int(self.price_box.toPlainText())
        tax = (self.tax_rate.value())
        total_price = price + ((tax / 100) * price)
        total_price_string = "The total price with tax is: " + str(total_price)
        self.results_window.setText(total_price_string)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

没有评论:

发表评论