簡體   English   中英

創建自定義PyQt5圖像按鈕

[英]Creating Custom PyQt5 image-button

我正在嘗試創建自定義的PyQt5按鈕,但是遇到了在QMainWindow對象中顯示它的問題。 這是我正在嘗試的代碼:

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QMainWindow

class PicButton(QAbstractButton):
    def __init__(self, pixmap, parent=None):
        super(PicButton, self).__init__(parent)
        self.pixmap = pixmap

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(event.rect(), self.pixmap)

    def sizeHint(self):
        return self.pixmap.size()

class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.left = 0
        self.top = 0
        self.width = 800
        self.height = 800
        self.initUI()

    def initUI(self):
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)
        btn = PicButton('/home/user/Desktop/Untitled.png')
        btn.move(0, 0)
        btn.resize(80,80)
        self.show()


app = QApplication(sys.argv)
window = App()

如果您僅使用window = Widget()並將按鈕對象放在其中,則該按鈕將起作用,如此答案所示: 如何在PyQt中編碼圖像按鈕?

根據您的代碼,您必須將QPixmap傳遞給PicButton,此外,如果您要移動它,它還應告訴您,如果傳遞父母,它將在相對於父親的那個位置放置,但不會通過。畫。

要解決該問題,您必須更改:

btn = PicButton('/home/user/Desktop/Untitled.png')

至:

btn = PicButton(QPixmap('/home/user/Desktop/Untitled.png'), self)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM