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:

Qt Code:
  1. #include <QWidget>
  2. #include <QColor>
  3.  
  4. class ColorPreviewWidget : public QWidget
  5. {
  6. public:
  7.  
  8. ColorPreviewWidget
  9. (
  10. const QColor & preview_color = Qt::white,
  11. QWidget *parent = 0
  12. );
  13.  
  14. void setColor(const QColor& new_color);
  15.  
  16. protected:
  17.  
  18. void paintEvent(QPaintEvent* event);
  19.  
  20. private:
  21.  
  22. QColor color;
  23. };
To copy to clipboard, switch view to plain text mode 

ColorPreviewWidget.cpp:

Qt Code:
  1. #include "ColorPreviewWidget.h"
  2. #include <QPainter>
  3. #include <QDebug>
  4.  
  5. ColorPreviewWidget::ColorPreviewWidget
  6. (
  7. const QColor & new_color,
  8. QWidget *parent
  9. )
  10. :
  11. QWidget(parent),
  12. color(new_color)
  13. {}
  14.  
  15. void ColorPreviewWidget::setColor(const QColor & new_color)
  16. {
  17. color = new_color;
  18. qDebug() << "setColor : color = " << color;
  19. // This debug message shows the right color (= new_color)
  20. }
  21.  
  22. void ColorPreviewWidget::paintEvent(QPaintEvent* e)
  23. {
  24. qDebug() << "paintEvent : color = " << color;
  25. // This debug message shows the wrong, default color, over
  26. // and over again!
  27. QPainter painter(this);
  28. painter.fillRect(0, 0, size().width(), size().height(), color);
  29. }
To copy to clipboard, switch view to plain text mode