[英]Circular image as button PyQt5
I'm trying to create a circular button with an image.我正在尝试创建一个带有图像的圆形按钮。 So far I've been able to create a circular button and a button with an image background but I haven't been able to combine the two.
到目前为止,我已经能够创建一个圆形按钮和一个带有图像背景的按钮,但我无法将两者结合起来。
Here is my current code:这是我当前的代码:
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 documentation has a section exactly about this topic : Qt 文档中有一个部分是关于这个主题的:
When styling a QPushButton, it is often desirable to use an image as the button graphic.
在设置 QPushButton 样式时,通常需要使用图像作为按钮图形。 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.
尝试使用 background-image 属性是很常见的,但这有很多缺点:例如,背景通常会隐藏在按钮装饰后面,因为它不被视为背景。 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 属性,因为无论背景如何,它都会始终显示图像(如果背景中有 alpha 值,您可以将其与背景组合),并且它具有处理按钮调整大小的特殊设置.
So, you must ensure that you're using a square (not rectangular) image with the circle margins right at the edges, and use border-image
instead of background-image
(which tiles the image if it's smaller than the button size);因此,您必须确保您使用的是方形(不是矩形)图像,边缘处有圆形边距,并使用
border-image
而不是background-image
(如果图像小于按钮大小,则平铺图像); note that you should not set any border in the stylesheet.请注意,你不应该设置任何边界的样式表。
button.setStyleSheet('''
border-image: url(image.png);
''')
You obviously need to always use the same value for both the height and the width of the button, possibly by using setFixedSize()
, otherwise if you add the button to a layout it will not be circular any more.您显然需要始终对按钮的高度和宽度使用相同的值,可能通过使用
setFixedSize()
,否则如果您将按钮添加到布局中,它将不再是圆形的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.