PySide6 QPushButton with Icon in Center

125 Views Asked by At

I'm trying to design a button that has a bigger icon, slightly above the center of the button, with some small text below it.

enter image description here

Minimum example:

from pathlib import Path
from PySide6.QtWidgets import (QPushButton, QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QWidget)
import sys


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setMinimumSize(400, 400)
        layoutV = QVBoxLayout()
        layoutH = QHBoxLayout()
        layoutV.addLayout(layoutH)
        btn = QPushButton(self)
        btn.setMinimumSize(200, 200)
        btn.setMaximumSize(200, 200)
        layoutH.addWidget(btn)
        container = QWidget()
        container.setLayout(layoutV)
        container.setStyleSheet("background: black;")
        self.setCentralWidget(container)

        path_to_image = Path("example.png")
        assert path_to_image.exists()

        btn.setStyleSheet(
            """
            QPushButton{
                        background: #0E0E0E;
                        border-radius: 10px;
                        background-image: url("example.png");
                        background-position: center;
                        background-repeat: no-repeat;
                        color: white;
                        text-align: bottom;
                        font: 18px;
                        padding-bottom: 15px;
                        }
            """)
        btn.setText("Icon Example")



app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

the problem is in the style sheets (i think).

background-position: center;

puts it in the dead center, as expected.

enter image description here

background-position: center top;

puts it on the top, but there is no way of padding-top this.

enter image description here

Is there a way of putting it slightly (+10/15% or 15-20px) above the center of the button? Mid-way between "center" and "top" would probably be the best. Googling did not return anything relevant except a thread from 2006 ... https://www.qtcentre.org/threads/41910-QStyleSheets-background-position-using-pixels-problem with no answers.

0

There are 0 best solutions below