0%

PyQt5的一些技巧

之前在公司有需求用pyqt5编写图形化界面,学习了一下,总结了一些经验

1.编写环境pycharm + qtdesigner

环境安装
pip3 install pyqt5-tools
会自动下载PyQt5和相关依赖包

安装完成后测试一下

1
2
3
4
5
6
7
8
9
import sys
from PyQt5 import QtWidgets

app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
w.resize(400, 100)
w.setWindowTitle("PyQt5 test")
w.show()
exit(app.exec_())

扩展配置
Qtdesigner、PyUIC配置

打开PyCharm,打开File—>Settings—>External Tools,点击加号来添加自己的工具,做如下配置:
Name:QtDesigner
Programs: python安装路径\Lib\site-packages\pyqt5_tools\Qt\bin\designer.exe
Working directory:$ProjectFileDir$

designer.exe路径:site-packages\pyqt5_tools\Qt\bin
报错no Qt platform plugin
将pyqt5_tools\Qt\plugins\platforms中的两个文件复制替换到与designer.exe同级的platforms文件夹中

Name:PyUIC
Program: python安装路径\python.exe
Parameters: -m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py
PyUIC可以将ui文件转化为py文件。

使用时右键ui文件选择PyUIC工具即可将ui文件转化为py文件。

2.信号与槽

测试脚本

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: utf-8 -*-
# @Time : 2020/12/11 17:03
# @Author : lockcy

from PyQt5.QtCore import QObject, pyqtSignal

class CustSignal(QObject):
signal1 = pyqtSignal()
signal2 = pyqtSignal(int)
signal3 = pyqtSignal(int, str)
signal4 = pyqtSignal(list)
signal5 = pyqtSignal(dict)
signal6 = pyqtSignal([int,str], [str])

def __init__(self, parent=None):
super(CustSignal, self).__init__(parent)
self.signal1.connect(self.signalCall1)
self.signal2.connect(self.signalCall2)
self.signal3.connect(self.signalCall3)
self.signal4.connect(self.signalCall4)
self.signal5.connect(self.signalCall5)
self.signal6[int, str].connect(self.signalCall6)
self.signal6[str].connect(self.signalCall6Overload)

self.signal1.emit()
self.signal2.emit(1)
self.signal3.emit(1, "text")
self.signal4.emit([1, 2, 3, 4])
self.signal5.emit({"username": "aa", "password": "bb"})
self.signal6[int, str].emit(1, "text")
self.signal6[str].emit("text")

def signalCall1(self):
print("signal1 emit")
def signalCall2(self, val):
print("signal2 emit,value:", val)
def signalCall3(self, val, text):
print("signal3 emit,value:", val, text)
def signalCall4(self, val):
print("signal4 emit,value:", val)
def signalCall5(self, val):
print("signal5 emit, value:", val)
def signalCall6(self, val, text):
print("signal6 emit, value:", val, text)
def signalCall6Overload(self, val):
print("signal6 overload emit,value:", val)

if __name__ == '__main__':
custSignal = CustSignal()

3.渐入渐出及打开界面

https://blog.csdn.net/qq_42719459/article/details/107691338