Issue
I am struggling to understand something seemingly simple:
I have a custom widget subclassing from QPushButton, multiple instances of which I am laying out in a QGridLayout(). The moment I add a paint() function and draw a background color to fill the button's rect() the layout's spacing does not seem to have an effect anymore.
Here is a screen shot to show what I mean:
This shows default QPushButtons that obey the layout's spacing and my custom "buttons" that don't. I'm sure I just need to (re)implement something in my CustomButton but can't find what it is. I tried setting contentMargins to no avail.
What am I missing? Maybe I need to not fill self.rect() but something else? Here is the example code that produces above screen shot:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class CustomButton(QPushButton):
def __init__(self, tool, icon=None, parent=None):
super(CustomButton, self).__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.setMinimumWidth(200)
self.frameGeometry()
def paintEvent(self, event):
painter = QPainter(self)
bgColor = QColor(60, 60, 60)
painter.fillRect(self.rect(), bgColor)
app = QApplication(sys.argv)
mainWindow = QWidget()
grid = QGridLayout()
grid.setSpacing(10)
mainWindow.setLayout(grid)
for i in xrange(4):
btn1 = CustomButton('A')
btn2 = QPushButton('B')
grid.addWidget(btn1, 0, i)
grid.addWidget(btn2, 1, i)
mainWindow.show()
sys.exit(app.exec_())
Solution
so a solution seems to be to manually adjust self.rect() to be a bit smaller, though I don't understand why this is necessary as I thought that's what the layout's spacing is for:
def paintEvent(self, event):
rect = self.rect()
rect.adjust(5,5,-5,-5)
painter = QPainter(self)
bgColor = QColor(60, 60, 60)
painter.fillRect(rect, bgColor)
This will give me the spacing I need. If anybody can shed light on whether this is a bug or a feature I'd be quite grateful.
Answered By - Frank Rueter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.