pyqt5实现按钮添加背景图片以及背景图片的切换

简介

对与控件QPushButton中的可以使用setStyleSheet设置它背景图片。具体设置背景图片的方法有两种

self.button.setStyleSheet("QPushButton{background-image: url(img/1.png)}")

然而对于这种方法背景图片无法进行边框的自适应,可以使用下面的方法

self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}")

可以做到自适应边框。

代码

代码里面有两个图片需要使用,我放在下面了

代码1

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

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()  # 界面绘制交给InitUi方法

    def initUI(self):
        # 设置窗口的位置和大小
        self.setGeometry(300, 300, 300, 220)
        # 设置窗口的标题
        self.setWindowTitle('QPushButton')

        #控件QPushButton的定义和设置
        self.button = QPushButton(self)
        self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}"
                                  "QPushButton:hover{border-image: url(img/1_1.png)}" 
                                  "QPushButton:pressed{border-image: url(img/1_1.png)}")
        #设置控件QPushButton的位置和大小
        self.button.setGeometry(100, 100, 50, 50)




if __name__ == '__main__':
    # 创建应用程序和对象
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

具体实现了按钮背景图片,以及鼠标划过按钮的背景切换,以及按下按钮的背景切换。

然而在按下按钮,我需要直接进行图片切换,且不回到原来的背景上。可以参考我的代码2。

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


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()  # 界面绘制交给InitUi方法
        self.slot_init()

    def initUI(self):
        # 设置窗口的位置和大小
        self.setGeometry(300, 300, 300, 220)
        # 设置窗口的标题
        self.setWindowTitle('QPushButton')

        #控件QPushButton的定义和设置
        self.button = QPushButton(self)
        self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}"
                                  "QPushButton:hover{border-image: url(img/1_1.png)}")

        # 设置控件QPushButton的位置和大小
        self.button.setGeometry(100, 100, 50, 50)

    def slot_init(self):
        self.button.clicked.connect(self.button_change)

    def button_change(self):
        # 切换图标变亮
        self.button.setStyleSheet('QPushButton{border-image:url(img/1_1.png)}')



if __name__ == '__main__':
    # 创建应用程序和对象
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

如果需要来回的切换,可以定义一个计数器来解决这个问题

猜你喜欢

转载自blog.csdn.net/pursuit_zhangyu/article/details/83213401