Skip to content

Instantly share code, notes, and snippets.

@leixingyu
Created December 5, 2021 23:43
Show Gist options
  • Save leixingyu/009a594f3d94643d39b9eee5ac6cf118 to your computer and use it in GitHub Desktop.
Save leixingyu/009a594f3d94643d39b9eee5ac6cf118 to your computer and use it in GitHub Desktop.
class MyButton(QtWidgets.QPushButton):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
def setPixmap(self, pixmap):
self.pixmap = pixmap
def sizeHint(self):
parent_size = QtWidgets.QPushButton.sizeHint(self)
return QtCore.QSize(parent_size.width() + self.pixmap.width(), max(parent_size.height(), self.pixmap.height()))
def paintEvent(self, event):
QtWidgets.QPushButton.paintEvent(self, event)
pos_x = 5 # hardcoded horizontal margin
pos_y = (self.height() - self.pixmap.height()) / 2
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, True)
painter.drawPixmap(pos_x, pos_y, self.pixmap)
class TestUI(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TestUI, self).__init__(parent)
# initialization object
layout = QtWidgets.QGridLayout()
pb = MyButton('test')
path = r"xxx"
pixmap = QtGui.QPixmap(path).scaled(40, 40, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
pb.setPixmap(pixmap)
layout.addWidget(pb)
self.setLayout(layout)
@bebetor
Copy link

bebetor commented Oct 5, 2022

in case you don't assign an icon, but use this class for all buttons, I've added a try-excpet block:

def sizeHint(self):
       parent_size = QPushButton.sizeHint(self)
       try:
           return QSize(
               parent_size.width() + self.pixmap.width(),
               max(parent_size.height(),
                   self.pixmap.height()))
       except AttributeError as error:
           return QSize(
               parent_size.width(),
               parent_size.height())
           logging.debug(error)

and

def paintEvent(self, event):
        QPushButton.paintEvent(self, event)

        try:
            pos_x = 5  # hardcoded horizontal margin
            pos_y = (self.height() - self.pixmap.height()) / 2

            painter = QPainter(self)
            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
            painter.drawPixmap(pos_x, pos_y, self.pixmap)
        except AttributeError as error:
            logging.debug(error)

thanx for your work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment