圆形图像作为按钮 PyQt5

Circular image as button PyQt5

我正在尝试创建一个带有图像的圆形按钮。 到目前为止,我已经能够创建一个圆形按钮和一个带有图像背景的按钮,但我无法将两者结合起来。

这是我当前的代码:

import sys
import PyQt5.QtWidgets


class Window(PyQt5.QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        # setting title
        self.setWindowTitle("Python ")

        # setting geometry
        self.setGeometry(100, 100, 600, 400)

        # calling method
        self.UiComponents()

        # showing all the widgets
        self.show()

    # method for widgets
    def UiComponents(self):
        button = PyQt5.QtWidgets.QPushButton("CLICK", self)
        button.setGeometry(200, 150, 100, 100)

        # Background img and circular
        button.setStyleSheet('''border-radius : 5;
        border : 2px solid black
        background-image : url(image.png);
        ''')

        # adding action to a button
        button.clicked.connect(self.clickme)

    # action method
    def clickme(self):
        print("pressed")



App = PyQt5.QtWidgets.QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

Qt 文档中有一节完全 about this topic:

When styling a QPushButton, it is often desirable to use an image as the button graphic. It is common to try the background-image property, but this has a number of drawbacks: For instance, the background will often appear hidden behind the button decoration, because it is not considered a background. In addition, if the button is resized, the entire background will be stretched or tiled, which does not always look good.

It is better to use the border-image property, as it will always display the image, regardless of the background (you can combine it with a background if it has alpha values in it), and it has special settings to deal with button resizing.

因此,您必须确保您使用的是正方形(而非矩形)图像,圆圈边距位于边缘,并使用 border-image 而不是 background-image(平铺图像如果它小于按钮尺寸);请注意,您应该在样式表中设置任何边框。


    button.setStyleSheet('''
        <b>border-image</b>: url(image.png);
        ''')

您显然需要始终对按钮的高度和宽度使用相同的值,可以使用 setFixedSize(),否则如果您将按钮添加到布局中,它将不再是圆形的.