How PySide6 paintEvent function for a PushButton works?

386 Views Asked by At

A long time ago, I wanted to make a logo appear on top of the text in a QPushButton stacked on top of each other, but I couldn't find anyway

  • I read some stylesheets (couldn't find a single doc to read it all about all styles I can apply to a button)
  • tried the setLayoutDirection (RightToLeft and LeftToRight were there, but no UpToDown direction)
  • In my (I wish) last attempt I tried to inherit a QAbstractButton (I didn't find QAbstractPushButton, so I guess QAbstractButton is the answer) and change its paintEvent/paintEngine to draw an image or maybe add a vbox inside it as a layout to draw to components, but I can't find anything in python (specially PySide) which has an example in any possible way close to that. The best thing I found was the analogue clock example which was not very helpful because it was trying to work a QWidget and not a QAbstractButton and I want to keep the feel of a Native looking button.

I like my final product to be something like this.

Enaml based example image

source of the implemention of that

Python Enaml toolkit supported this feature out of the box (in one of its widgets), and I know it is QT based, so I really wish to know how it is possible?

p.s.: Also, is there a market for qt widgets? e.g.: a plugin system. Because rewriting an android like switch doesn't seem like the correct thing that I should do! even a good tutorial or doc would be appreicated (excluding official doc)

1

There are 1 best solutions below

1
On

It is easier than you think, you can use QToolButton() like this:

import sys

from PySide6.QtCore import Qt, QSize
from PySide6.QtWidgets import QApplication, QVBoxLayout,QStyle, QWidget, 
QToolButton

class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        
        button = QToolButton()
       
        # here you choose the position of the icon and its text
        button.setToolButtonStyle(
        Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
    
        # here I just use built-in icon by PySide6 for this example
        name = 'SP_DialogSaveButton'
        pixmapi = getattr(QStyle, name)
        icon = self.style().standardIcon(pixmapi)
        
        # here we set text and icon of size 32x32 to the button 
        button.setIcon(icon)
        button.setText("Sample text")
        button.setIconSize(QSize(32, 32))
        
        # finally we add our button to the layout
        lay = QVBoxLayout(self)
        lay.addWidget(button, alignment=Qt.AlignCenter)

if __name__ == "__main__":

    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec())

enter image description here