使用QgraphicsView子类绘制QPAINTER线

Draw a line with QPainter using QGraphicsView subclass

本文关键字:QPAINTER 绘制 子类 QgraphicsView 使用      更新时间:2023-10-16

问题:我无法称呼GraphicsView的paintEvent,换句话说,我不知道如何使qpainter完全工作。

  • 我正在使用QTCreator的设计师将QgraphicsView放入主窗口。
  • i子类Qgraphicsview(class Draw)覆盖paintEvent并在主窗口中保存此子类(Draw draw)的实例(我想将复杂的图纸移动到其他地方)
  • 我创建了一个new QGraphicsScene并将其分配给QGraphicsView'sui->graphicsViewdraw),因此当我在Draw中绘制时,它也会在
    ui->graphicsview中显然生效(我希望)。
  • 我敢肯定,当我使用新的scene对象绘制时,我会得到一个可见的结果(但是,我不想使用scene对象进行绘制,而是QPainter。原因是另一个问题,所以我希望这不是必不可少的),因此我试图将QGraphicsView分类并覆盖油漆,因此我很容易获得QPainter p(this)
  • 发生事件时,我在Window.cpp中致电MyRepaint(),我试图在我的Draw对象上调用paintEvent() - 但它不起作用。

主窗口'window.cpp':

Window::Window(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::Window),
    draw(*this)  //my own QGraphicsView instance (see class below)
{
    ui->setupUi(this);
    //assigning a new scene to draw and to window's graphicsView
    this->scene = new QGraphicsScene(this);
    this->draw.setScene(scene);
    this->ui->graphicsView->setScene(scene);
}
void Window::MyRepaint()
{
    qInfo() << "Repaint - start" << this->draw.scene();
    this->draw.scene()->update(this->draw.sceneRect());
    this->draw.repaint();
    this->draw.viewport()->update();
    /*only the following line made the paintEvent executed eventually but without a visible result and with an error in the output*/
    this->draw.paintEvent(NULL);
    qInfo() << "Repaint - end"; 
}

子分类qgraphicsview,文件:draw.h:

class Window;
class Draw : public QGraphicsView{
private:
    Window& parent;
public:
    Draw(Window &parent);
    void paintEvent(QPaintEvent*e) override;
};

draw.cpp

void Draw::paintEvent(QPaintEvent *e)
{
    qInfo() << "trying to draw";
    QPainter p(this);
    p.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
    p.drawLine(0, 0, 200, 200);
}

输出:

Repaint - start QGraphicsScene(0x15c7eca8)
trying to draw
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setPen: Painter not active
QPainter::viewport: Painter not active
QPainter::end: Painter not active, aborted
Repaint - end

也许我选择了一种完全错误的方法。

qgraphicsView旨在与qgraphicsscene一起使用。如果您只想绘制线条,那么源自Qwidget并覆盖它的油漆。在设计师中将Qwidget推广到您的派生类。

另外,QT有一个很好的文档。我建议您访问此页面。

简而

这是图形视图绘制线路的框架方式,而接受的答案是Qwidget方式

QgraphicsView是葡萄视图框架的一部分。通常通过调用update(),小部件可以触发paintevent()。但是,据我所知,在图形视图框架中,QgraphicsView不可能通过调用update()

来触发paintevent()

根据QT文档,您应该知道还有一件事:

警告:当油漆evice是小部件时,qpainter只能在paintevent()函数中或paintevent()

称为paintevent()函数中使用