问题描述
我正在尝试创建带有图像的圆形按钮。 到目前为止,我已经能够创建一个圆形按钮和一个具有图像背景的按钮,但是我无法将两者结合在一起。
这是我当前的代码:
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)
# 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:
设计QPushButton的样式时,通常希望将图像用作按钮图形。尝试使用background-image属性是很常见的,但这有许多缺点:例如,背景通常会隐藏在按钮装饰后面,因为它不被视为背景。此外,如果调整按钮的大小,则整个背景将被拉伸或平铺,但效果并不总是很好。
最好使用border-image属性,因为它将始终显示图像,而不管背景如何(如果其中包含alpha值,则可以将其与背景结合使用),并且需要进行特殊设置调整按钮的大小。
因此,您必须确保使用的是正方形(而不是矩形)的图像,其边缘处的圆圈为空白,并使用border-image
而不是background-image
(如果图像是小于按钮大小);请注意,您应该不要在样式表中设置任何边框。
button.setStyleSheet('''
border-image: url(image.png);
''')
您显然需要始终使用按钮的高度和宽度使用相同的值,可能使用setFixedSize()
;否则,如果将按钮添加到布局中,它将不再是圆形的。 / p>