在QGraphicsView上绘制一个矩形(或任何东西)

时间:2015-02-22 03:44:19

标签: qt drawing qt-creator

我正在使用QtCreator构建接口应用程序。

我只是习惯了Qt,并试图在QtGraphicsView上绘制东西。

由于我使用编辑器创建了界面,因此我在代码中检索我的对象(请告诉我这是不是错误)。

this->m_graphView = this->findChild<QGraphicsView *>("graphicsView");
this->m_graphScene = this->m_graphView->scene();

我在界面上有按钮,并且已经创建了插槽以响应点击的事件。

我只想在MainWindow上的图形视图上绘制一些东西(几何:[(10,10),320x240])。

我一直在网上阅读例子,但我无法做任何事情。

我目前的代码如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->m_graphView = this->findChild<QGraphicsView *>("graphicsView");
    this->m_graphScene = this->m_graphView->scene();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnDown_clicked()
{
    qDebug() << "STUB : button DOWN";

    m_graphScene->addLine(0, 0, 42, 42, QPen(QBrush(Qt::black),1));
    m_graphView->show();
}

void MainWindow::on_btnLeft_clicked()
{
    qDebug() << "STUB : button LEFT";
}

void MainWindow::on_btnUp_clicked()
{
    qDebug() << "STUB : button UP";
}

void MainWindow::on_btnRight_clicked()
{
    qDebug() << "STUB : button RIGHT";
}

void MainWindow::on_btnShoot_clicked()
{
    qDebug() << "STUB : button SHOOT";
}

但令人讨厌的是,它并没有绘制任何内容,我甚至在调用addLine方法时出现此错误

QGraphicsScene::addItem: item has already been added to this scene

我的代码和/或我的做事方式有什么问题? 我只是想画一些东西,但不能成功,谢谢。

1 个答案:

答案 0 :(得分:3)

以表格

检索小部件

您可以更轻松地获取graphicsView指针(及其场景) “ui”成员具有指向.form文件中排列的小部件的指针 (如果您愿意,请参阅“ui_mainwindow.h”文件)

// assign to pointer
QGraphicsView *view = ui->graphicsView;
view->...

// or directly (I like this)
ui->graphicsView->...

所以,Mainwindow类不需要“m_graphicsView”成员。

图形视图

QGraphicsView需要设置场景。(首先没有场景)
我们必须自己创建QGraphicsScene 所以Mainwindow类需要“m_graphicsScene”成员。

m_graphicsScene = new QGraphicsScene(this);
ui->graphicsView->setScene(m_graphicsScene);

绘图更容易

如果您只想绘制某些内容,可以覆盖“paintEvent”方法 PaintEvent是QWidget的虚方法。

在.h文件中

protected:
    void paintEvent(QPaintEvent *event);

在.cpp文件中:

void MainWindow::paintEvent(QPaintEvent *event)
{
    // unuse
    Q_UNUSED(event);

    // pass "this" pointer to painter
    QPainter painter(this); 

    // setPen
    // QPen can take "Qt::black" directly as first arg (without QBrush() constructor)
    painter.setPen(QPen(Qt::black), 1);

    // draw line
    painter.drawLine(0, 0, 42, 42);
}

请享受Qt!