使用QGraphicsView子类用QPainter绘制一条线

时间:2016-06-23 02:49:09

标签: c++ qt qgraphicsview qpainter

问题: 我无法调用GraphicsView的paintEvent,换句话说,我不知道如何让QPainter完全工作。

  • 我正在使用qtcreator的设计器将QGraphicsView放入主窗口。
  • 我对QGraphicsView(class Draw)进行了分类,覆盖了paintEvent并在主窗口中保存了这个子类的实例(Draw draw)(我想将复杂的绘图移到别处)
  • 我创建了new QGraphicsScene并将其分配给QGraphicsView'sui->graphicsViewdraw),所以当我在Draw内部绘制时,它会明显生效在ui->graphicsview中也是如此(我希望)。
  • 我确定当我使用新的scene对象绘制时,我得到一个可见的结果(但是,我不想使用scene对象进行绘制,而是{{1}我之所以希望它不是必要的,所以我试图将QPainter子类化并重写paintEvent,以便轻松获得QGraphicsView
  • 当事件发生时,我在QPainter p(this)中致电MyRepaint()我试图在Window.cpp对象上调用paintEvent() - 但它无效。

主窗口'Window.cpp':

Draw

继承QGraphicsView,文件:Draw.h:

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

Draw.cpp

class Window;
class Draw : public QGraphicsView{
private:
    Window& parent;

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

输出:

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

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

2 个答案:

答案 0 :(得分:3)

QGraphicsView旨在与QGraphicsScene一起使用。如果你只想绘制线条,那么从QWidget派生并覆盖它的paintEvent。在设计师中将QWidget推广到派生类。

另外,Qt有很好的文档。我建议您访问this页面。

答案 1 :(得分:0)

简而言之,您可以使用QGraphicsLineItem *QGraphicsScene::addLine(...)

这是Graphics View Framwork画线的方式,而可接受的答案是QWidget方式

QGraphicsView是Grapics View Framework的一部分。通常,通过调用update(),小部件能够触发paintEvent()。但是,据我所知,在Graphics View Framework中,QGraphicsView不可能通过调用update()来使paintEvent()变成老虎机。

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

警告:当paintdevice是窗口小部件时,QPainter只能在paintEvent()函数内部或paintEvent()调用的函数中使用

相关问题