0lan
0lan

Reputation: 229

Remove the strange one-pixel space around QPushButton with PySide/PyQT on Windows

This is my current code.

import sys
from PySide6.QtWidgets import (
    QApplication,
    QGridLayout,
    QProgressBar,
    QPushButton,
    QTableWidget,
    QWidget
)


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Example")
        layout = QGridLayout()
        layout.setContentsMargins(6, 6, 6, 6)
        layout.addWidget(QTableWidget(), 0, 0, 1, 3)
        bar = QProgressBar()
        bar.setValue(50)
        bar.setTextVisible(False)
        layout.addWidget(bar, 1, 0, 1, 2)
        btn = QPushButton("OK")
        layout.addWidget(btn, 1, 2, 1, 1)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

And as you can see there is a strange one-pixel space around the button.

Is there a way to delete it?

I tried using CSS and putting negative margins without success.

Upvotes: 0

Views: 138

Answers (1)

musicamante
musicamante

Reputation: 48231

That completely depends on the QStyle, apparently on Windows push buttons have a slightly bigger margin than other widgets.

This cannot be solved by using stylesheets, unless you provide the full stylesheet with borders for all button states (normal, pressed, disabled, etc).

There are only two solutions: bypass the painting on the widget, or use a proxystyle.

paintEvent() override

class BiggerButton(QtWidgets.QPushButton):
    def paintEvent(self, event):
        if self.style().proxy().objectName() != 'windowsvista':
            super().paintEvent(event)
            return
        opt = QtWidgets.QStyleOptionButton()
        self.initStyleOption(opt)
        opt.rect.adjust(-1, -1, 1, 1)
        qp = QtWidgets.QStylePainter(self)
        qp.drawControl(QtWidgets.QStyle.CE_PushButton, opt)

class Window(QtWidgets.QWidget):
    def __init__(self):
        # ...
        btn = BiggerButton("OK")

QProxyStyle

class Proxy(QtWidgets.QProxyStyle):
    def drawControl(self, ctl, opt, qp, widget=None):
        if ctl == self.CE_PushButton:
            opt.rect.adjust(-1, -1, 1, 1)
        super().drawControl(ctl, opt, qp, widget)

# ...
app = QtWidgets.QApplication(sys.argv)
if app.style().objectName() == 'windowsvista':
    app.setStyle(Proxy())

Upvotes: 1

Related Questions