Qt4, QtCreator
I am trying to draw inside Widget:
void Widget::on_pushButton_clicked()
{
QPainter painter;
painter.begin(ui->label);
QRectF rectangle(10.0, 20.0, 80.0, 60.0);
int startAngle = 30 * 16;
int spanAngle = 120 * 16;
painter.drawArc(rectangle, startAngle, spanAngle);
painter.end();
}
But when I press button nothing happens.
How to do this right way?
If you overwrite the paint-method as described by Arnold Spence, you should call the parent's paintEvent or you end up with a widget that only shows your rectangle on a white background.
You need to override paintEvent() and do your painting there. You don't really need the
begin()
andend()
. Declare the painter withThe constructor will handle
begin()
, andend()
will be called when thepainter
object goes out of scope and is destroyed.You also won't need the click event to trigger the painting.
paintEvent()
will be called whenever the widget needs to draw itself. You could use the the button click to toggle a boolean that thepaintEvent()
checks to determine whether or not it should display the rectangle and arc. Just make sure you callupdate()
after you toggle the variable.UPDATE:
To avoid having to override the
paintEvent()
of a widget, you could use aQLabel
and assign a pixmap to it and paint to that. Note: As far as I can tell, you will need to set the pixmap each time you modify it.