Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt4 How to draw inside a widget?

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?

like image 789
Astronavigator Avatar asked Oct 08 '10 22:10

Astronavigator


People also ask

How do you draw a shape in Qt?

In the constructor we create and initialize the various widgets appearing in the main application window. First we create the RenderArea widget that will render the currently active shape. Then we create the Shape combobox, and add the associated items (i.e. the different shapes a QPainter can draw).


2 Answers

You need to override paintEvent() and do your painting there. You don't really need the begin() and end(). Declare the painter with

QPainter painter(this);

The constructor will handle begin(), and end() will be called when the painter 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 the paintEvent() checks to determine whether or not it should display the rectangle and arc. Just make sure you call update() after you toggle the variable.

void Widget::on_pushButton_clicked()
{
    drawShapes = !drawShapes;
    update();
}

void Widget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    if(drawShapes)
    {
        QRectF rectangle(10.0, 20.0, 80.0, 60.0);
        int startAngle = 30 * 16;
        int spanAngle = 120 * 16;
        painter.drawArc(rectangle, startAngle, spanAngle);
    }
}

UPDATE:

To avoid having to override the paintEvent() of a widget, you could use a QLabel 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.

void MainForm::slot_buttonClick()
{
    QPixmap pixmap(100,100);
    pixmap.fill(QColor("transparent"));

    QPainter painter(&pixmap);
    painter.setBrush(QBrush(Qt::black));
    painter.drawRect(10, 10, 100, 100);

    label.setPixmap(pixmap);
}
like image 122
Arnold Spence Avatar answered Oct 19 '22 22:10

Arnold Spence


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.

like image 20
Sebastian Negraszus Avatar answered Oct 19 '22 23:10

Sebastian Negraszus