[英]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 文檔中有一個部分是關於這個主題的:
在設置 QPushButton 樣式時,通常需要使用圖像作為按鈕圖形。 嘗試使用 background-image 屬性是很常見的,但這有很多缺點:例如,背景通常會隱藏在按鈕裝飾后面,因為它不被視為背景。 此外,如果調整按鈕大小,整個背景將被拉伸或平鋪,這並不總是很好看。
最好使用 border-image 屬性,因為無論背景如何,它都會始終顯示圖像(如果背景中有 alpha 值,您可以將其與背景組合),並且它具有處理按鈕調整大小的特殊設置.
因此,您必須確保您使用的是方形(不是矩形)圖像,邊緣處有圓形邊距,並使用border-image
而不是background-image
(如果圖像小於按鈕大小,則平鋪圖像); 請注意,你不應該設置任何邊界的樣式表。
button.setStyleSheet('''
border-image: url(image.png);
''')
您顯然需要始終對按鈕的高度和寬度使用相同的值,可能通過使用setFixedSize()
,否則如果您將按鈕添加到布局中,它將不再是圓形的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.