Creating Custom PyQt5 image-button

8.5k Views Asked by At

I'm trying to create a custom PyQt5 button, but am running across problems displaying it in a QMainWindow object. Here's the code I'm trying:

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()

The button will work if you just use window = Widget()and put the button object in there as is shown in this answer: how code a Image button in PyQt?

1

There are 1 best solutions below

0
On BEST ANSWER

According to your code you must pass a QPixmap to your PicButton, In addition to them if you are going to move it should tell you where, if you pass the parent, it will place in that position relative to the father, but will not be drawn.

To solve the problem you must change:

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

to:

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