【发布时间】:2016-06-23 02:49:09
【问题描述】:
问题: 我无法调用 GraphicsView 的 paintEvent,或者换句话说,我不知道如何让 QPainter 完全工作。
- 我正在使用 qtcreator 的设计器将 QGraphicsView 放置到主窗口中。
- 我将 QGraphicsView (
class Draw) 子类化为覆盖paintEvent并在主窗口中保存此子类 (Draw draw) 的实例(我想将复杂的绘图移至其他位置) - 我创建了一个
new QGraphicsScene并将其分配给QGraphicsView's(ui->graphicsView和draw),所以当我在Draw内绘图时,它也会在ui->graphicsview中明显生效(我希望)。 - 我确定当我使用新的
scene对象进行绘图时,我会得到一个可见的结果(但是,我不想使用scene对象进行绘图,而是使用QPainter。原因是另一个问题,所以我希望它不是必需的)因此我试图继承QGraphicsView并覆盖paintEvent,以便我轻松获得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;
};
绘制.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
也许我选择了一个完全错误的方法。
【问题讨论】:
标签: c++ qt qgraphicsview qpainter