2017-04-03 108 views
0
//oneLed.h 
#pragma once 

#include<QPushButton> 

class oneLed :public QPushButton 
{ 
    Q_OBJECT 

public: 
    oneLed(QWidget* parent = 0); 
protected: 
    void doPainting(); 
}; 

#include"oneLed.h" 
#include<QPainter> 
oneLed::oneLed(QWidget* parent) 
    :QPushButton(parent) 
{ 
    connect(this, &QPushButton::clicked, this, &oneLed::doPainting); 
} 

void oneLed::doPainting() 
{ 
     QPainter painter(this); 
     //painter.setRenderHint(QPainter::Antialiasing); 
     painter.setPen(QPen(QBrush("#888"), 1)); 
     painter.setBrush(QBrush(QColor("#888"))); 
     painter.drawEllipse(0, 0, this->width(), this->height()); 
     //painter.drawEllipse(0, 0, 30, 30); 

} 

//main.cpp 
#include"oneLed.h" 
#include <QtWidgets/QApplication> 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    oneLed w; 
    w.resize(100, 500); 
    w.show(); 
    return a.exec(); 
} 

我想達到以下效果:當我點擊oneLed對象 ,圓出現在oneled對象的位置。當我再次單擊oneLed對象時,圓圈消失。如何在QPushButton點擊位置繪製一個形狀?

但事實上,當我點擊oneLed對象時,圓圈不會出現。

回答

1

我想你錯了。什麼發生在你的代碼是:

  • 點擊按鈕時,你的doPainting槽被調用
  • 你做你的風俗畫
  • 實際按鈕漆事件是由Qt的主事件循環觸發,並覆蓋你的畫

您需要覆蓋paintEvent方法。

在您的自定義插槽中,引發一個表示按鈕已被按下的布爾標誌。

void oneLed::slotClicked() 
{ 
    m_clicked = !m_clicked; 
} 

然後做這樣的事情:

void oneLed::paintEvent(QPaintEvent *event) 
{ 
    // first render the Qt button 
    QPushButton::paintEvent(event); 
    // afterward, do custom painting over it 
    if (m_clicked) 
    { 
     QPainter painter(this); 
     painter.setPen(QPen(QBrush("#888"), 1)); 
     painter.setBrush(QBrush(QColor("#888"))); 
     painter.drawEllipse(0, 0, this->width(), this->height()); 
    } 
} 
1

的方法您實現是paintEvent,在doPainting必須更改標誌,並調用update()方法插槽。

重要:方法調用paintEvent

oneLed.h

#ifndef ONELED_H 
#define ONELED_H 

#include <QPushButton> 

class oneLed : public QPushButton 
{ 
    Q_OBJECT 
public: 
    oneLed(QWidget* parent = 0); 

protected: 
    void paintEvent(QPaintEvent * event); 

private slots: 
    void doPainting(); 

private: 
    bool state; 
}; 

#endif // ONELED_H 

oneLed.cpp

#include "oneled.h" 
#include <QPainter> 

oneLed::oneLed(QWidget *parent):QPushButton(parent) 
{ 
    state = false; 
    connect(this, &QPushButton::clicked, this, &oneLed::doPainting); 
} 

void oneLed::paintEvent(QPaintEvent *event) 
{ 
    QPushButton::paintEvent(event); 
    if(state){ 
     QPainter painter(this); 
     //painter.setRenderHint(QPainter::Antialiasing); 
     painter.setPen(QPen(QBrush("#888"), 1)); 
     painter.setBrush(QBrush(QColor("#888"))); 
     painter.drawEllipse(0, 0, width(), height()); 
    } 

} 

void oneLed::doPainting() 
{ 
    state = !state; 
    update(); 
} 
+0

click事件已經調用控件重繪 –