[Qt-interest] MyQWidget's paintEvent will not be called if ...

Andreas Pakulat apaku at gmx.de
Wed Mar 11 20:48:39 CET 2009


On 12.03.09 01:35:04, James Yan wrote:
> hey all,
>   i write a widget public from QWidget to show a picture, so my code looks
> like this:
> 
> //constructor
> ImageWidget::ImageWidget(QWidget *parent,QImage* pImage) : QWidget(parent)
> {
>     m_pImage = pImage;
>     setFixedSize(1,1);      // MUST GIVE A SIZE, OTHERWISE PaintEvent WILL
> NOT BE CALLED!
> }
> 
> //paint event
> void ImageWidget::paintEvent(QPaintEvent * /* event */)
> {
>     //get the painter
>     QPainter painter(this);
> 
>     //draw the image
>     if(m_pImage)
>     {
>         QImage
> img(m_pImage->bits(),m_pImage->width(),m_pImage->height(),m_pImage->format());
>         painter.drawImage(QPoint(0,0),img);
>         setFixedSize(m_pImage->width(),m_pImage->height());
>     }
> }
> 
> then, i put the widget in a scrollArea of a mainwindow, what a fun that i
> found if i did not give the widget a fixed size in it's constructor, then my
> picture will not be painted out, in other word, the paintEvent will alwasy
> not be called! i do not know why, i think it maybe a bug or something.

Its not a bug. A widget has no size (i.e. size == 0,0) by default hence
any code that has such a widget as child and is being asked to draw
itself and all of its children is free to ignore such a childwidget with
no size - and hence no area to paint. As you don't add a
layout+subwidgets your widget never has any reason to adjust its size. A
better way to fix this is to set the size according to your image or if
the image may change you should probably override the sizeHint() method
to return the current image's size.

Andreas

-- 
You have the body of a 19 year old.  Please return it before it gets wrinkled.



More information about the Qt-interest-old mailing list