2012-07-10 155 views
0

我努力理解看似簡單的東西的工作:定製油漆()不QLayout.setSpacing()

我有一個從QPushButton自定義窗口小部件的子類,多個實例由本人在QGridLayout佈局() 。當我添加paint()函數並繪製背景色以填充按鈕的rect()時,佈局的間距似乎不再有效果。 這裏是一個截屏,顯示我的意思: enter image description here

這表明,服從佈局的間距和我的自定義「按鈕」不默認QPushButtons。 我確定我只需要(重新)在我的CustomButton中實現某些內容,但無法找到它的內容。我嘗試設置contentMargins無濟於事。

我錯過了什麼?也許我不需要填寫self.rect()而是其他的東西? 下面是上面的屏幕截圖產生的示例代碼:

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_()) 
+0

您的示例按照我的預期工作..也許您需要一個更新的PySide? (也可能是一個操作系統特定的問題) – Luke 2012-07-10 21:37:23

+0

有趣的是,謝謝(我在OSX 1.0.4 pyside上) – 2012-07-11 01:05:21

+0

有沒有人可以重現這個問題?無論我做主窗口的寬度如何,我都沒有在自定義按鈕之間找到任何間距。 – 2012-07-13 04:21:44

回答

0

這樣的解決方案似乎是手動調節self.rect()是小了些,但我不明白爲什麼這是必要的,因爲我認爲這是佈局的間距是:

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) 

這會給我我需要的間距。如果有人能夠說明這是一個錯誤還是一個功能,我會很感激。