2017-08-24 68 views
0

問題

我想創建一個按鈕小部件,具有以下要素:是否可以從子類和父類中繪製QWidget?

  • 配置背景顏色
  • 按鈕尺寸,透明圖標
  • 可配置定位文本

因爲我更喜歡QPushButton而不是QToolButton,所以我面臨着已知的問題(請參閱herehere)圖標/文本對齊。

所以我的做法是專門QPushButton類和覆蓋paintEvent方法(請參閱下面的代碼)。如果我只需手動繪製文本並將剩下的部分(圖標和背景)留給父類,那就太好了。但是,現在似乎沒有畫出文字。

這是可能的,我的錯誤是在別的地方,還是我必須自己畫?

代碼

class MyPushButton : public QPushButton 
{ 
public: 
    MyPushButton() : QPushButton() {} 
    virtual ~MyPushButton() = default; 

protected: 
    virtual void paintEvent(QPaintEvent* e) override { 
     QPushButton::paintEvent(e); 
     QPainter p(this); 
     p.drawText(0,0, "label"); 
    } 
}; 

回答

1

Ofcourse,你可以這樣做:

這裏MyPushButton從QPushButton的。

void MyPushButton::paintEvent(QPaintEvent *e) 
{ 
    // This will draw everything on the push button with default palette. 
    QPushButton::paintEvent(e); 

    // Anything draw past this statement will be drawn over the real 
    // push button with all its properties intact, 
    // if you won't draw anything over, your pushbutton will look like QPushButton 
    // Now draw your custom content here: 
} 

編輯1: 嘗試了這一點,使用矩形告訴在哪裏畫: 雖然我不知道爲什麼它不與點工作。

class MyPB : public QPushButton 
{ 
protected: 
    void paintEvent(QPaintEvent *e) override 
    { 
     // This will draw everything on the push button with default palette. 
     QPushButton::paintEvent(e); 
     p.drawText(QRect(0,0, 50, 50), "HelloWorld"); 

    } 
}; 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 

    MyPB pb; 
    pb.show(); 

    return a.exec(); 
} 

編輯2: 它與點爲好,它已經工作了按設計。 所以,它在0,0位置寫的文字,並顯示如下:

The button when text "HelloWorld" painted at 0,0 location

所以,如果你看到,繪製文本,但它是按鈕的尺寸之外,因此可以沒有看到它。

+0

我也這麼認爲,但沒有成功。也許我在這裏畫了一些錯誤的東西: 'QPainter p(this);' 'p.drawText(0,0,「label」);' – bunto1

+1

編輯作品,是的,我會標記即被接受。爲什麼這個問題不起作用將是另一個問題。謝謝! – bunto1

+0

@ bunto1:的確,如果你想出來的話,請詳細說明:) – PRIME