PyQt5美化你的GUI界面

本文展示了使用PyQt5创建多种图形界面元素的示例,包括圆点选择、选项按钮、关闭弹窗、设置关闭按钮、背景设置、下拉列表框和等待时的进度条。通过这些代码参考,读者可以了解如何实现基本的GUI功能,如按钮、对话框和进度反馈,为自己的应用增添交互性。

目录

1 圆点选择选项设置

2 选项按钮设置

3 关闭弹窗设置

4 关闭程序弹窗

5 设置关闭按钮

6 设置背景

7 下拉列表框设置

8 等待时显示进度条


1 圆点选择选项设置

效果展示

代码参考

#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *

class qt_view(QWidget):
    def __init__(self):
        super(qt_view, self).__init__()

        self.resize(600, 250)
        self.setWindowTitle("圆点选择")

        self.radioButton_1 = QtWidgets.QRadioButton(self)
        self.radioButton_1.setGeometry(QtCore.QRect(230, 100, 89, 16))
        self.radioButton_1.setStyleSheet("font-family:微软雅黑; color:black;")
        self.radioButton_1.setObjectName("radioButton_1")
        self.radioButton_2 = QtWidgets.QRadioButton(self)
        self.radioButton_2.setGeometry(QtCore.QRect(310, 100, 89, 16))
        self.radioButton_2.setStyleSheet("font-family:微软雅黑; color:black;")
        self.radioButton_2.setObjectName("radioButton_2")

        translate = QtCore.QCoreApplication.translate
        self.radioButton_1.setText(translate("Form", "选项1"))
        self.radioButton_2.setText(translate("Form", "选项2"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    my = qt_view()
    my.show()
    app.exec_()

2 选项按钮设置

效果展示

代码参考

import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *

class qt_view(QWidget):
    def __init__(self):
        super(qt_view, self).__init__()
        self.resize(600, 250)
        self.setWindowTitle("圆灰按钮")

        button_open_img = QPushButton(self)
        button_open_img.setText("打开图片")
        button_open_img.move(250, 100)
        button_open_img.setFixedSize(150, 50)
        button_open_img.setStyleSheet("QPushButton{\n"
                                    "    background:orange;\n"
                                    "    color:white;\n"
                                    "    box-shadow: 1px 1px 3px;font-size:18px;border-radius: 24px;font-family: 微软雅黑;\n"
                                    "}\n"
                                    "QPushButton:pressed{\n"
                                    "    background:black;\n"
                                    "}")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    my = qt_view()
    my.show()
    app.exec_()

3 关闭弹窗设置

效果展示

代码参考

import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *

class qt_view(QWidget):
    def __init__(self):
        super(qt_view, self).__init__()
        print("关闭弹窗")
        result = QMessageBox.question(self, "注意!", "您真的要关闭吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if result == QMessageBox.Yes:
            QMessageBox.information(self, "消息", "谢谢使用!")
            quit()
        else:
            QMessageBox.information(self, "消息", "正在返回...")
            quit()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    my = qt_view()
    my.show()
    app.exec_()

4 关闭程序弹窗

效果展示

代码参考

from PyQt5 import QtWidgets
import sys

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(600, 320)

class Dialog(QtWidgets.QMainWindow):
    def closeEvent(self, event):
        reply = QtWidgets.QMessageBox.question(self,
                                               '本程序',
                                               "是否要退出程序?",
                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                               QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    dialog = Dialog()
    ui = Ui_Dialog()
    ui.setupUi(dialog)
    dialog.show()
    sys.exit(app.exec_())

5 设置关闭按钮

效果展示

代码参考

import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class gui_view(QWidget):
    def __init__(self):
        super(gui_view, self).__init__()

        self.resize(500, 350)
        self.setWindowFlags(Qt.FramelessWindowHint)  # 去边框
        # # self.setAttribute(Qt.WA_TranslucentBackground)  # 设置窗口背景透明

        button_red = QPushButton(self)
        button_red.move(20, 20)
        button_red.setFixedSize(20, 20)
        button_red.setStyleSheet("QPushButton{\n"
                                         "    background:#CE0000;\n"
                                         "    color:white;\n"
                                         "    box-shadow: 1px 1px 3px;border-radius: 10px;\n"
                                         "}\n"
                                         "QPushButton:hover{                    \n"
                                         "    background:red;\n"
                                         "}\n"
                                         "QPushButton:pressed{\n"
                                         "    border: 1px solid #3C3C3C!important;\n"
                                         "    background:black;\n"
                                         "}")
        button_red.clicked.connect(self.quit_button)

        button_orange = QPushButton(self)
        button_orange.move(50, 20)
        button_orange.setFixedSize(20, 20)
        button_orange.setStyleSheet("QPushButton{\n"
                                 "    background:orange;\n"
                                 "    color:white;\n"
                                 "    box-shadow: 1px 1px 3px;border-radius: 10px;\n"
                                 "}\n"
                                 "QPushButton:hover{                    \n"
                                 "    background:yellow;\n"
                                 "}\n"
                                 "QPushButton:pressed{\n"
                                 "    border: 1px solid #3C3C3C!important;\n"
                                 "    background:black;\n"
                                 "}")

        button_green = QPushButton(self)
        button_green.move(80, 20)
        button_green.setFixedSize(20, 20)
        button_green.setStyleSheet("QPushButton{\n"
                                    "    background:green;\n"
                                    "    color:white;\n"
                                    "    box-shadow: 1px 1px 3px;border-radius: 10px;\n"
                                    "}\n"
                                    "QPushButton:hover{                    \n"
                                    "    background:#08BF14;\n"
                                    "}\n"
                                    "QPushButton:pressed{\n"
                                    "    border: 1px solid #3C3C3C!important;\n"
                                    "    background:black;\n"
                                    "}")

    def quit_button(self):
        quit()

if __name__ == '__main__':
    app2 = QtWidgets.QApplication(sys.argv)
    my = gui_view()
    my.show()
    app2.exec_()

6 设置背景

效果展示

代码参考

import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *
from PyQt5 import QtGui

class gui_view(QWidget):
    def __init__(self):
        super(gui_view, self).__init__()
        self.resize(1200, 750)
        # self.setStyleSheet("background-image: url(:F:/background.jpg);")
        self.setWindowTitle("设置背景图片")
        window_pale = QtGui.QPalette()
        window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap("F:/background.jpg")))
        self.setPalette(window_pale)

if __name__ == '__main__':
    app2 = QtWidgets.QApplication(sys.argv)
    my = gui_view()
    my.show()
    app2.exec_()

7 下拉列表框设置

效果展示

代码参考

import sys
from PyQt5.QtWidgets import QWidget, QComboBox, QApplication

class ComboxDemo(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('下拉列表框')
        self.resize(700, 400)

        # 实例化QComBox对象
        self.cb = QComboBox(self)
        self.cb.move(100, 20)

        # 单个添加条目
        self.cb.addItem('选项1')
        self.cb.addItem('选项2')
        # 多个添加条目
        self.cb.addItems(['选项3', '选项4', '选项5'])

        self.cb.currentIndexChanged[str].connect(self.print_value)  

    def print_value(self, value):
        print(value)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    comboxDemo = ComboxDemo()
    comboxDemo.show()
    sys.exit(app.exec_())

8 等待时显示进度条

效果展示

代码参考

from PyQt5.QtWidgets import QMainWindow, QProgressBar, QApplication, QLabel, QStatusBar, QPushButton
import sys

class SampleBar(QMainWindow):
    def __init__(self, parent=None):
        super(SampleBar, self).__init__(parent)
        self.setMinimumSize(400, 100)
        self.statusBar = QStatusBar()
        self.statusBar.setStyleSheet('QStatusBar::item {border: none;}')
        self.setStatusBar(self.statusBar)
        self.progressBar = QProgressBar()
        self.label = QLabel()
        self.label.setText("加载中,请稍后... ")
        self.statusBar.addPermanentWidget(self.label, stretch=2)
        self.statusBar.addPermanentWidget(self.progressBar, stretch=4)
        self.progressBar.setRange(0, 100)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(0)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = SampleBar()
    main.show()
    sys.exit(app.exec_())

持续更新中...

<think>我们被要求回答关于PyQt5GUI界面美化技巧和方法的问题。根据提供的引用,我们可以总结出以下几个关键点:1.使用QSS(QtStyle Sheets)进行样式设置,类似于CSS。2.使用布局管理器(如网格布局)来组织控件。 3.可以通过设置整个应用程序的样式表来统一风格。 此外,我们可以扩展一些常见的美化技巧,例如使用自定义控件、图标、背景图片、动画效果等。由于引用中提到了QSS语法,我们可以详细说明如何使用QSS来设置控件样式。同时,我们可以提供一些具体的例子,如设置按钮、标签等控件的样式。下面我们将按照以下结构组织回答:1.QSS基础:介绍QSS的基本语法和使用方法。 2.布局管理:说明如何通过布局管理器创建整洁的界面。 3.美化技巧:提供一些具体的美化技巧,如设置字体、颜色、边框、背景等。4.资源使用:介绍如何使用图标、图片等资源。5.高级技巧:提及一些高级技巧,如自定义控件、动画效果等。 最后,我们将生成相关问题。</think>### PyQt5 GUI界面美化技巧与方法 PyQt5提供了多种方式美化GUI界面,核心方法是通过**QSS样式表**(类似CSS)和**布局管理器**实现视觉优化。以下是关键技巧: #### 一、QSS样式表基础应用 1. **控件级样式** 为单个控件设置样式(如按钮): ```python button = QPushButton("美化按钮") button.setStyleSheet(""" QPushButton { background-color: #4CAF50; /* 背景色 */ border-radius: 8px; /* 圆角 */ font: bold 14px "微软雅黑"; /* 字体 */ padding: 10px 20px; } QPushButton:hover { background-color: #45a049; } /* 悬停效果 */ """) ``` 2. **全局样式** 统一设置整个应用的样式: ```python app = QApplication([]) app.setStyleSheet(""" QLabel { color: #2c3e50; font-size: 14px; } QLineEdit { border: 1px solid #3498db; border-radius: 4px; } """) ``` #### 二、布局与结构优化 1. **使用网格布局** 创建规整的控件排列(引用示例[^2]): ```python layout = QGridLayout() layout.addWidget(QPushButton("Button 1"), 0, 0) # 第0行第0列 layout.addWidget(QPushButton("Button 2"), 0, 1) # 第0行第1列 layout.addWidget(QPushButton("Button 3"), 1, 0, 1, 2) # 跨2列 ``` 2. **间距与边距控制** ```python layout.setSpacing(10) # 控件间距 layout.setContentsMargins(20, 20, 20, 20) # 布局边距(左,上,右,下) ``` #### 三、进阶美化技巧 1. **动态效果** 添加过渡动画(需结合`QPropertyAnimation`): ```python animation = QPropertyAnimation(button, b"geometry") animation.setDuration(500) # 动画时长(ms) animation.setStartValue(QRect(0, 0, 100, 30)) animation.setEndValue(QRect(50, 50, 150, 50)) animation.start() ``` 2. **自定义组件** 继承现有控件创建个性化组件: ```python class GradientButton(QPushButton): def paintEvent(self, event): # 实现渐变背景绘制 painter = QPainter(self) gradient = QLinearGradient(0, 0, self.width(), 0) gradient.setColorAt(0, Qt.blue) gradient.setColorAt(1, Qt.cyan) painter.fillRect(self.rect(), gradient) super().paintEvent(event) ``` #### 四、资源整合 1. **图标与图片** 使用`QPixmap`添加视觉元素: ```python icon = QIcon("icon.png") button.setIcon(icon) label.setPixmap(QPixmap("background.jpg").scaled(300, 200)) ``` 2. **字体库支持** 加载外部字体: ```python font_id = QFontDatabase.addApplicationFont("custom_font.ttf") font_family = QFontDatabase.applicationFontFamilies(font_id)[0] app.setFont(QFont(font_family, 12)) ``` > **最佳实践**:建议将QSS样式保存在单独文件中,通过`app.setStyleSheet(open("style.qss").read())`加载,便于维护[^3]。
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荣仔!最靓的仔!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值