前言
自用的pyqt5界面优化美化代码,方便自己写界面时复制,也顺便造福广大网友吧!
首先安装基础工具:
Pycharm配置QtDesigner(PyUIC、PyRcc)
并懂得如何规范化创建qt界面:
QtDesigner规范创建应用界面
文章将持续更新.......
一、QtDesigner内的编程(QSS)
1. 按钮变化
#pushButton_create_user{
background-color: rgb(0, 0, 0);
color: rgb(255, 255, 255);
border: 3px solid rgb(0,0,0);
border-radius:10px
}
#pushButton_create_user:hover{
color: rgb(0, 0, 0);
background-color: rgb(255, 255, 255);
}
#pushButton_create_user:pressed{
padding-top:5px;
padding-left:5px
}
鼠标不置于其上效果:
鼠标置于其上但不点击效果:
点击效果(字体往右下角移动5px):
2.边框和圆角
border:2px solid rgb(186,186,186);
border-radius:10px
效果:
3.无边框和按住指令
#pushButton_login{
border:none;
}
#pushButton_login:focus{
color:rgb(186,186,186);
}
按住效果:
松开效果:
4.指定圆角和插入图片(拉伸和堆叠)
border-image: url(:/images/001.jpg);
border-top-left-radius:30px;
border-bottom-left-radius:30px
效果:
background-image: url(:/images/001.jpg);
border-top-left-radius:30px;
border-bottom-left-radius:30px
5.只有下划线的透明输入框
border:none;
border-bottom: 5px solid rgba(0,0,0,255);
background-color: rgba(0,0,0,0);
效果:
6.下拉菜单自定义格式
这个分为两个部分:
1. 表面框的编写
#comboBox_project{
border-radius:11px;
background-color: rgb(184, 184, 184);
color: rgb(56,56,56);
}
#comboBox_project:hover{
border-radius:0px;
background-color: rgb(184, 184, 184);
border-top-left-radius:10px;
border-top-right-radius:10px;
border-bottom-right-radius:10px;
color: rgb(56,56,56);
}
#comboBox_project::drop-down{
border-top-right-radius:5px;
border-bottom-right-radius:5px;
background-color: rgb(40, 40, 40);
color: rgb(40,40,40);
min-width:30px;
}
#comboBox_project::down-arrow{
image: url(:/icons/arrow-down-filling.png);
height:18px;
width:18px;
}
效果:
鼠标放上去后效果:
2.下拉内容框的编写
重点:
下拉内容框的编辑,因为只用QT表达式编辑是没有效果的,所以生成UI后必须要在py文件内加上这段。
self.newlist = QtWidgets.QListWidget()
self.comboBox_project.setModel(self.newlist.model())
self.comboBox_project.setView(self.newlist)
表达式:
#comboBox_project QAbstractItemView{
font-size:20px;
font-weight:bold;
}
#comboBox_project QAbstractItemView::item{
color: rgb(40, 40, 40);
height:30px;
selection-color: rgb(186,186,186);
background-color:rgb(80, 80, 80);
}
效果:
7.自用QSS(不做任何说明)
界面效果:
# 1
QLabel{
border-radius:4px;
background-color: rgb(80, 80, 80);
font: 20pt "微软雅黑";
font-weight:bold;
color: rgb(187,187,187);
}
QSlider::handle:horizontal{
background-color: rgb(80, 80, 80);
}
# 2
QPushButton{
border-radius:5px;
font: 14pt "微软雅黑";
font-weight:bold;
border:3px solid rgb(184,184,184);
background-color: rgb(184, 184, 184);
color: rgb(56,56,56);
}
QPushButton:hover{
border-radius:5px;
color: rgb(184, 184, 184);
background-color: rgb(56,56,56);
}
QPushButton:pressed{
padding-top:5px;
padding-left:5px;
}
# 3
#widget_status{
background-color: rgb(83, 83, 83);
border-top-left-radius:10px;
border-top-right-radius:10px;
}
#label_title{
color: rgb(183, 183, 183);
font: 25pt "微软雅黑";
font-weight:bold;
}
# 4
#comboBox_project{
border-radius:11px;
background-color: rgb(184, 184, 184);
color: rgb(56,56,56);
font: 15pt "微软雅黑";
font-weight:bold;
}
#comboBox_project:hover{
border-radius:0px;
background-color: rgb(184, 184, 184);
border-top-left-radius:10px;
border-top-right-radius:10px;
border-bottom-right-radius:10px;
color: rgb(56,56,56);
}
#comboBox_project::drop-down{
border-top-right-radius:5px;
border-bottom-right-radius:5px;
background-color: rgb(40, 40, 40);
color: rgb(40,40,40);
min-width:30px;
}
#comboBox_project::down-arrow{
image: url(:/icons/arrow-down-filling.png);
height:18px;
width:18px;
}
#comboBox_project QAbstractItemView{
font: 15pt "微软雅黑";
font-weight:bold;
}
#comboBox_project QAbstractItemView::item{
color: rgb(40, 40, 40);
height:30px;
selection-color: rgb(186,186,186);
background-color:rgb(80, 80, 80);
}
二、py文件内的编程
1.创建无边框效果
MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)
添加至开头:
效果(结合2的图片来看):
2.创建阴影效果
self.label.setGraphicsEffect(QtWidgets.QGraphicsDropShadowEffect(blurRadius=25, xOffset=0, yOffset=0))
self.pushButton_login.setGraphicsEffect(QtWidgets.QGraphicsDropShadowEffect(blurRadius=25, xOffset=3, yOffset=3))
添加至末尾:
效果:
3.无边框拖动效果(全界面均可)
def __init__(self): # 在初始化方法中设定m_flag为false
super().__init__()
self.m_flag = False
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton and self.isMaximized() == False:
self.m_flag = True
self.m_position = event.globalPos() - self.pos()
event.accept()
self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
def mouseMoveEvent(self, mouse_event):
if QtCore.Qt.LeftButton and self.m_flag:
self.move(mouse_event.globalPos() - self.m_position)
mouse_event.accept()
def mouseReleaseEvent(self, mouse_event):
self.m_flag = False
self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
添加至调用类的设定中:
效果(无按钮和框的位置都可以进行长按移动):
!!!注意:若是初始化方法没有定义m_flag为False,直接拖动窗口内的按钮,程序将会因为缺少m_flag参数而崩溃
4.无边框的最大化
首先先规范创建可自由变化的UI,不规范化创建,缩放必定有问题。
参考:QtDesigner规范创建应用界面
代码分两部分:
self.ui.pushButton_resize.clicked.connect(self.resize_win)
放置于类ui调用后。
def resize_win(self):
if self.isMaximized():
self.showNormal()
self.ui.pushButton_resize.setIcon(QtGui.QIcon(":/icons/fullscreen-expand.png"))
else:
self.showMaximized()
self.ui.pushButton_resize.setIcon(QtGui.QIcon(":/icons/fullscreen-shrink.png"))
放置于类方法函数即可。
效果:
5.滑动条显示数值
使用到了horizontalSlider和QLabel。
分为两块,都添加于PyUIC生成的UI文件中:
self.horizontalSlider_hole.valueChanged.connect(self.sl_value_hole)
用ctrl+F快速寻找控件位置然后添加:
def sl_value_hole(self):
sl1 = self.horizontalSlider_hole.value()
sl2 = ' ' + str(sl1) + '%'
self.label_percent_hole.setText(sl2)
这个函数添加到末尾即可。
效果:
6.点击QLabel变化事件
在PyUIC生成的py文件内添加:
class MyQLabel(QtWidgets.QLabel):
# 自定义信号, 注意信号必须为类属性
button_clicked_signal = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(MyQLabel, self).__init__(parent)
self.i = 0
def mouseReleaseEvent(self, QMouseEvent):
self.i += 1
self.button_clicked_signal.emit(self.i)
# 可在外部与槽函数连接
def connect_customized_slot(self, func):
self.button_clicked_signal.connect(func)
ctrl+F迅速找到你要改的QLabel控件:
self.label = MyQLabel(self.widget)
self.label.connect_customized_slot(self.change_text)
在py最后(类方法)编写你要实现的函数,如我的,点击后更改文字:
def change_text(self, flag):
if flag % 2 == 1:
_translate = QtCore.QCoreApplication.translate
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(18)
self.label.setFont(font)
self.label.setText(_translate("MainWindow", "Design By LJK"))
else:
_translate = QtCore.QCoreApplication.translate
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(35)
font.setBold(False)
font.setItalic(False)
font.setWeight(9)
self.label.setFont(font)
self.label.setText(_translate("MainWindow", "APMH 2022"))
效果:
7.双击标题栏放大窗口,只有拖动标题栏才能移动窗口
重新定义Widget,放置于PyUIC生成的py文件中:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QStyleOption, QStyle
from PyQt5.QtGui import QPainter
from PyQt5.QtCore import pyqtSignal
# 定义标题栏
class MyWidget(QtWidgets.QWidget):
signal_resize = pyqtSignal(int)
signal_move = pyqtSignal(int, str)
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.setObjectName('widget_status')
self.db = 0
self.m_flag = False
# 重写paintEvent 否则不能使用样式表定义外观
def paintEvent(self, evt):
opt = QStyleOption()
opt.initFrom(self)
painter = QPainter(self)
# 反锯齿
painter.setRenderHint(QPainter.Antialiasing)
self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)
def mouseDoubleClickEvent(self, a0: QtGui.QMouseEvent) -> None:
self.db = 1
self.signal_resize.emit(self.db)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton and self.isMaximized() == False:
self.m_flag = True
self.m_position = event.pos()
event.accept()
self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
def mouseMoveEvent(self, QMouseEvent):
if QtCore.Qt.LeftButton and self.m_flag:
self.move_pos = QMouseEvent.globalPos() - self.m_position
self.move_pos = str(self.move_pos)
QMouseEvent.accept()
# 判断鼠标位置切换鼠标手势
self.signal_move.emit(1, self.move_pos)
def mouseReleaseEvent(self, QMouseEvent):
self.m_flag = False
self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
然后更改你的标题栏widget为MyWidget。
与新写的mainwindow类进行对接,写在类初始化方法内:
self.ui.widget_status.signal_resize.connect(self.resize_db)
self.ui.widget_status.signal_move.connect(self.move_lf)
将以下写入mainwindow的类方法内:
def move_lf(self, flag, m_pos):
move_pos = m_pos
str_pos = move_pos[20:].split(', ')
int_x_pos = int(str_pos[0])
int_y_pos = int(str_pos[1][:-1])
if flag == 1:
self.move(QPoint(int_x_pos, int_y_pos))
def resize_win(self):
if self.isMaximized():
self.showNormal()
self.ui.pushButton_resize.setIcon(QtGui.QIcon(":/icons/fullscreen-expand.png"))
else:
self.showMaximized()
self.ui.pushButton_resize.setIcon(QtGui.QIcon(":/icons/fullscreen-shrink.png"))
def resize_db(self, flag):
if flag == 1:
self.resize_win()
效果:
8.根据屏幕尺寸设置打开时窗口大小
因为程序要用去不同的电脑,屏幕分辨率会有差别,故而需要自适应调整:
self.desktop = QApplication.desktop()
self.screenRect = self.desktop.screenGeometry()
self.screenheight = self.screenRect.height()
self.screenwidth = self.screenRect.width()
self.height = int(self.screenheight * 0.5) # 这里改变比例
self.width = int(self.screenwidth * 0.5)
print("Screen height {}".format(self.screenheight))
print("Screen width {}".format(self.screenwidth))
self.resize(self.width, self.height)
放置于重写类的setupUi后:
效果:
(效果会局限于你缩写的控件最小大小)
9.自由拉伸无边框应用的尺寸
先看效果:
首先还是先规范化创建窗口并打开MouseTracking:点击查看教程
写入mainwindow初始化方法中:
self._padding = 7 # 设置边界宽度为7
self.initDrag()
写入mainwindow类方法:
def initDrag(self):
# 设置鼠标跟踪判断扳机默认值,可以直接写入初始化方法中
self._move_drag = False
self._corner_drag = False
self._bottom_drag = False
self._right_drag = False
def mousePressEvent(self, event):
# 重写鼠标点击的事件
if (event.button() == Qt.LeftButton) and (event.pos() in self._corner_rect):
# 鼠标左键点击右下角边界区域
self._corner_drag = True
event.accept()
elif (event.button() == Qt.LeftButton) and (event.pos() in self._right_rect):
# 鼠标左键点击右侧边界区域
self._right_drag = True
event.accept()
elif (event.button() == Qt.LeftButton) and (event.pos() in self._bottom_rect):
# 鼠标左键点击下侧边界区域
self._bottom_drag = True
event.accept()
def mouseMoveEvent(self, QMouseEvent):
# 判断鼠标位置切换鼠标手势
if QMouseEvent.pos() in self._corner_rect:
self.setCursor(Qt.SizeFDiagCursor)
elif QMouseEvent.pos() in self._bottom_rect:
self.setCursor(Qt.SizeVerCursor)
elif QMouseEvent.pos() in self._right_rect:
self.setCursor(Qt.SizeHorCursor)
else:
self.setCursor(Qt.ArrowCursor)
# 当鼠标左键点击不放及满足点击区域的要求后,分别实现不同的窗口调整
if Qt.LeftButton and self._right_drag:
# 右侧调整窗口宽度
self.resize(QMouseEvent.pos().x(), self.height())
QMouseEvent.accept()
elif Qt.LeftButton and self._bottom_drag:
# 下侧调整窗口高度
self.resize(self.width(), QMouseEvent.pos().y())
QMouseEvent.accept()
elif Qt.LeftButton and self._corner_drag:
# 右下角同时调整高度和宽度
self.resize(QMouseEvent.pos().x(), QMouseEvent.pos().y())
QMouseEvent.accept()
elif Qt.LeftButton and self._move_drag:
# 标题栏拖放窗口位置
self.move_lf(QMouseEvent.globalPos() - self.move_DragPosition)
QMouseEvent.accept()
def mouseReleaseEvent(self, QMouseEvent):
self._move_drag = False
self._corner_drag = False
self._bottom_drag = False
self._right_drag = False
10.创建图标
参考自:PyQt5 设置软件图标(左上角、任务栏)、软件主窗口标题
from PyQt5.QtGui import QIcon
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
class WinMain(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setWindowIcon(QIcon("./ICON.png"))
self.setWindowTitle(_translate("MainWindow", "expressionRecognition")) #第二个参数:窗口标题
效果:
任务栏上:文章来源:https://www.toymoban.com/news/detail-435348.html
文章来源地址https://www.toymoban.com/news/detail-435348.html
到了这里,关于pyqt5优化美化界面代码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!