//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对象时,圆圈消失了。
但实际上,当我点击oneLed对象时,圆圈并没有出现。
我想你弄错了。代码中发生的情况是:
- 单击按钮并调用您的 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());
}
}
您实现的方法paintEvent
,在doPainting
的插槽中,您必须更改标志并调用 update()
方法。
重要: update
方法调用paintEvent
。
一莱德·
#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
一个领导.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();
}