Qt4如何在小部件内部绘制? [英] Qt4 How to draw inside a widget?

查看:223
本文介绍了Qt4如何在小部件内部绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Qt4,QtCreator

Qt4, QtCreator

我试图在Widget中绘制:

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?

推荐答案

您需要覆盖 paintEvent()并在那里做绘画。你并不需要 begin() end()。用

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);

构造函数将处理 begin(),和 end()将在画家对象超出范围并被销毁时被调用。

The constructor will handle begin(), and end() will be called when the painter object goes out of scope and is destroyed.

您也不需要点击事件来触发绘画。当小部件需要绘制自己时, paintEvent()将被调用。您可以使用按钮点击来切换 paintEvent()检查的布尔值,以确定它是否应显示矩形和弧线。请确保在切换变量后调用 update()

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);
    }
}

更新:

为了避免必须覆盖小部件的 paintEvent(),可以使用 QLabel 并为其分配一个像素图并对其进行绘制。注意:据我所知,每次修改时都需要设置pixmap。

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);
}

这篇关于Qt4如何在小部件内部绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆