Pyqt5學習筆記(1)_安裝和初步使用
阿新 • • 發佈:2022-05-07
PyQt5
1、PyQt5、Pyinstaller安裝配置
1.1安裝
#安裝pyqt5和拓展工具的的包
pip install PyQt5 -i https://pypi.douban.com/simple
pip install PyQt5-tools -i https://pypi.douban.com/simple
#安裝pyqt5打包程式,可以將程式打包成exe
pip install pyinstaller
1.2環境變數配置
把PyQt5-tools的安裝目錄新增到系統環境變數Path中
測試是否安裝成功
import sys from PyQt5 import QtWidgets, QtCore app = QtWidgets.QApplication(sys.argv) widget = QtWidgets.QWidget() widget.resize(360,360) widget.setWindowTitle("hello, pyqt5") widget.show() sys.exit(app.exec_())
出現這種視窗則安裝成功
(注:pycharm中F9可以指定當前檔案執行)
1.3在pycharm上配置
在pycharm上配置qt工具,可以更加方便的使用qtdesigner,轉換檔案,打包檔案
File->Settings->Tools->External Tools
1.3.1配置qtdesigner
Name:可自己定義
program:Qt Designer的安裝路徑
一般是D:\Program Files (x86)\Python38-32\Scripts\pyuic5.exe
arguements:不填
directory: $FileDir$
1.3.2配置pyuic
補充pyuic命令解析
-m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py
說明:
-m表示呼叫某個模組,這裡表示呼叫PyQt5.uic.pyuic模組
$FileName$ 表示需要轉換的原始檔名稱
-o表示生成目標檔案
$FileNameWithoutExtension$ 需要轉換的原始檔名詞不包函拓展名
拓展名通過.py使得生成檔案是py檔案
Name:可自己定義 program:pyuic的安裝路徑 一般是D:\Program Files (x86)\Python38-32\Scripts\pyuic5.exe arguements:$FileName$ -o $FileNameWithoutExtension$.py directory: $FileDir$
1.3.3配置pyinstaller
Name:可自己定義
program:pyinstaller的安裝路徑
一般是D:\Program Files (x86)\Python38-32\Scripts\pyinstaller.exe
arguements:-F $FileNameWithoutExtension$.py
directory:$FileDir$
2、Qt Designer設計師介面
2.1開啟qtdesigner
dialog 對話方塊視窗 用於子視窗
main window 主視窗 有選單欄、工具欄。。功能豐富、較複雜
widget 介面 簡單通用
視窗部件 更多模板 用於子視窗
2.2工具使用
拖拽部件 點選部件 左側物件、屬性檢視
物件檢視器 物件名 類名
屬性編輯器 可以設定屬性
屬性 geometry [(x,y),ab] 距離左邊畫素 距離上畫素 寬度高度
使用後儲存為.ui檔案
2.3pyuic生成檔案
命令列使用pyuic5 -o test01.py test01.ui
即pyuic5 -o {輸出檔名} {輸入designer設計好的.ui字尾介面檔案}
如果pycharm配置好,不用命令列輸入,在ui檔案右擊,external tools->pyuic直接執行
配置好的qt工具,在執行過程中相當於在控制檯輸入命令
生成的程式碼
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test01.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
#objectname 視窗名稱 視窗是例項化物件
Form.setObjectName("Form")
#設定寬高
Form.resize(400, 300)
#重新轉變ui
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
#呼叫Qtcore
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
2.4實際使用
#匯入python系統類庫
import sys
#匯入pyqt5用到的類庫, QApplication應用程式類 QWidget控制元件基類
from PyQt5.QtWidgets import QApplication, QWidget
#匯入生成介面的類模組
import test01
#例項化一個類,建構函式傳入python的應用引數
#print(sys.argv) #這裡列印包函當前檔案絕對路徑的列表
app=QApplication(sys.argv)
#例項化介面基類類
w=QWidget()
#例項化生成介面的類 裝載
form = test01.Ui_Form()
form.setupUi(w)
w.show()
#app.exec_() 表示程式監聽事件的開始,是一個死迴圈
sys.exit(app.exec_())
3、總結
1、Qtdesigner設計介面與pyuic轉換後代碼對應關係
2、pyqt5常用函式基本用法
3、如何呼叫生成介面的思想