创建自定义PyQt5图像按钮

时间:2017-06-09 08:44:58

标签: python pyqt pyqt5 qwidget qabstractbutton

我正在尝试创建一个自定义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()并将按钮对象放在那里,按钮将会起作用,如下面的答案所示:how code a Image button in PyQt?

1 个答案:

答案 0 :(得分:0)

根据您的代码,您必须将QPixmap传递给您的PicButton,除了它们之外,如果您要移动它应该告诉您,如果您通过父级,它将放置在相对于父亲的那个位置,但是将不会被绘制。

要解决此问题,您必须更改:

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

为:

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