How QT draws on controls (such as QLabel, Button, QWidget, etc.)

method one:

Use event filtering mechanism

Event filter:

An operation composed of two functions, used to complete the event monitoring of a component to other components, the two functions are installEventFilter();

eventFilter(QObject *obj, QEvent *ev)

All are functions in the QObject class.

how to use:

One, ui->paint_widget (sub-control name)->installEventFilter(this); //Install event filter   

Second, add in .h

bool eventFilter(QObject *watched, QEvent *event);

Three, implement in .cpp

bool Form2::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->widget && event->type() == QEvent::Paint)//发生绘图事件,且是在widget上发生的
        {

        QPainter painter(ui->widget);

        // 设置画笔样式
        QPen pen(Qt::red);
        pen.setWidth(3);
        painter.setPen(pen);

        // 绘制圆形
        QRectF rectangle(10.0, 20.0, 80.0, 80.0);    // 圆形所在矩形位置和大小
        painter.drawEllipse(rectangle);

        return true;
        }
    else
        return false;

}

Fourth, pay attention to the premise of use: because when we judge

event->type() == QEvent::Paint judges the drawing event

So you need to call the drawing event to take effect

void Form2::paintEvent(QPaintEvent *)
{
    // 创建QPainter对象并在其中进行绘图
        QPainter painter(ui->widget);

        // 设置画笔样式
        QPen pen(Qt::red);
        pen.setWidth(3);
        painter.setPen(pen);

        // 绘制圆形
        QRectF rectangle(10.0, 20.0, 80.0, 80.0);    // 圆形所在矩形位置和大小
        painter.drawEllipse(rectangle);
}

Summary: It can be seen from the above that the implementation code in the drawing event is the same as the implementation code in the event filter, so it can be encapsulated into a function. Therefore, the method can be summarized as:

bool 类名::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->paint_widget && event->type() == QEvent::Paint)
    {
        Fun(想要绘图的指针名); //响应函数
    }
    return QWidget::eventFilter(watched,event);
}

//实现响应函数
void 类名::Fun(想要绘图的控件或窗口的类名 * 指针名)
{
   xxxxxxxxxxxxxxxxxx;
}


void 类名::paintEvent(QPaintEvent *)
{
    Fun(想要绘图的指针名);
}

Example: To draw in the widget (red frame part) in the Form window

 

Effect:

 

 

 

Method Two:

Define a class by yourself, let it inherit from the control class you want to achieve drawing

for example:

Define a MyWidget class that inherits from QWidget, and then rewrite the paintEvent(QPaintEvent *) function in this class, and draw in it. Then upgrade the corresponding QWidget to MyWidget in the ui interface.

Guess you like

Origin blog.csdn.net/qq_58136559/article/details/130458427