Hello,
I've created a custom widget. My goal was to simply draw a rectangle filled with color. I want the color to be changeable via setColor method, which is called from a slot of parent window object.
The problem is, that whenever paintEvent is called, the private member color is -- somehow -- initialized back to the value provided in constructor (Qt::white by default). That happens even though setColor method with a new color was called before the paintEvent. As a consequence, the widget is always painted in the same color that was provided in constructor.
I have also found a very similar unanswered question here:
http://stackoverflow.com/questions/1...mber-variables
What is causing the problem? What should I do in order to enable the color switching?
ColorPreviewWidget.h:
#include <QWidget>
#include <QColor>
class ColorPreviewWidget
: public QWidget{
public:
ColorPreviewWidget
(
const QColor & preview_color
= Qt
::white,
);
void setColor(const QColor& new_color);
protected:
private:
};
#include <QWidget>
#include <QColor>
class ColorPreviewWidget : public QWidget
{
public:
ColorPreviewWidget
(
const QColor & preview_color = Qt::white,
QWidget *parent = 0
);
void setColor(const QColor& new_color);
protected:
void paintEvent(QPaintEvent* event);
private:
QColor color;
};
To copy to clipboard, switch view to plain text mode
ColorPreviewWidget.cpp:
#include "ColorPreviewWidget.h"
#include <QPainter>
#include <QDebug>
ColorPreviewWidget::ColorPreviewWidget
(
)
:
color(new_color)
{}
void ColorPreviewWidget
::setColor(const QColor & new_color
) {
color = new_color;
qDebug() << "setColor : color = " << color;
// This debug message shows the right color (= new_color)
}
{
qDebug() << "paintEvent : color = " << color;
// This debug message shows the wrong, default color, over
// and over again!
painter.fillRect(0, 0, size().width(), size().height(), color);
}
#include "ColorPreviewWidget.h"
#include <QPainter>
#include <QDebug>
ColorPreviewWidget::ColorPreviewWidget
(
const QColor & new_color,
QWidget *parent
)
:
QWidget(parent),
color(new_color)
{}
void ColorPreviewWidget::setColor(const QColor & new_color)
{
color = new_color;
qDebug() << "setColor : color = " << color;
// This debug message shows the right color (= new_color)
}
void ColorPreviewWidget::paintEvent(QPaintEvent* e)
{
qDebug() << "paintEvent : color = " << color;
// This debug message shows the wrong, default color, over
// and over again!
QPainter painter(this);
painter.fillRect(0, 0, size().width(), size().height(), color);
}
To copy to clipboard, switch view to plain text mode
Bookmarks