qt在scrollArea中画线时遇到的问题

问题遇到的现象和发生背景

想法上:①在scollArea中的绿色button用动画体现,点击start绿色button移动到scrollArea的左上角
②点击绿色button会在scrollArea中出现一条红色直线
实际上:点击绿色button后不会出现完整的红线,之后点击scrollArea控件任意处才会出现红线
问题:代码哪里错了,怎么改

代码如下
  1. MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void MovePointButton();
    void paintline();
    void Respond();
protected:
    bool eventFilter(QObject *obj, QEvent *event);//事件过滤器函数
//    void paintEvent(QPaintEvent*);
private:
    Ui::MainWindow *ui;
    QPushButton*PointButton;
    QPropertyAnimation*anim;
};
#endif // MAINWINDOW_H


  1. MainWindow.cpp
#include "MainWindow.h"
#include "ui_MainWindow.h"

#include 
#include
#include
#include
#include
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->scrollArea->setStyleSheet(QString::fromUtf8("border:3px solid blue"));//设置边界颜色
    PointButton = new QPushButton(ui->scrollAreaWidgetContents);  //创建QPushButton控件
    PointButton->move(1000,20); //换个位置
    const QString button_style ="min-width:40px;min-height:40px;max-width:40px;max-height:40px;border-radius:20px;border:1px solid black;background:green";
    PointButton->setStyleSheet(button_style);
    PointButton->setText(tr("1"));  //设置控件文本
    PointButton->show();


    anim=new QPropertyAnimation(PointButton,"geometry");
    anim->setStartValue(PointButton->geometry());
    anim->setEndValue(QRect(0, 0, 0, 0));
    anim->setDuration(1000);

    connect(ui->StartButton,&QPushButton::clicked,this,&MainWindow::MovePointButton);
    connect(PointButton,&QPushButton::clicked,this,&MainWindow::Respond);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::MovePointButton()
{
    anim->start();
}
void MainWindow::paintline()
{
    QPainter painter(ui->scrollAreaWidgetContents);
    //设置画笔
    QPen penLine;
    penLine.setWidth(10); //线宽
    penLine.setColor(Qt::red); //划线颜色
    penLine.setStyle(Qt::SolidLine);//线的类型,实线、虚线等
    penLine.setCapStyle(Qt::FlatCap);//线端点样式
    penLine.setJoinStyle(Qt::BevelJoin);//线的连接点样式
    painter.setPen(penLine);
    painter.drawLine(0,0,1000, 800);
    qDebug()<<"999999999999999"<Respond()
{
    ui->scrollAreaWidgetContents->installEventFilter(this);//加入事件过滤器
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    //对象为ui->scrollAreaWidgetContents时,进行绘制事件,绘制函数为paintline,绘制返回完成的信号
    if(obj == ui->scrollAreaWidgetContents && event->type() == QEvent::Paint){paintline();}
    return QWidget::eventFilter(obj,event);
}

运行结果及报错内容

img

img

img


img