我正在使用 QtCreator 构建界面应用程序。
我刚刚习惯 Qt 并尝试在 QtGraphicsView 上绘制东西。
自从我使用编辑器创建界面以来,我正在像这样检索代码中的对象(请告诉我这是否错误)。
this->m_graphView = this->findChild<QGraphicsView *>("graphicsView");
this->m_graphScene = this->m_graphView->scene();
我在界面上有按钮,并且已经创建了插槽来对单击的事件使用react。
我只是想在主窗口上的图形 View 上绘制一些东西(任何东西)(几何图形:[(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:项目已添加到此场景
我的代码和/或我的做事方式有什么问题? 我只是想画点东西但画不出来,谢谢。
最佳答案
检索表单中的小部件
您可以更轻松地获取graphicsView指针(及其场景)。
“ui”成员具有指向 .form 文件中排列的小部件的指针。
(如果愿意,请参阅“ui_mainwindow.h”文件)
// assign to pointer
QGraphicsView *view = ui->graphicsView;
view->...
// or directly (I like this)
ui->graphicsView->...
所以,Mainwindow类不需要“m_graphicsView”成员。
图形 View
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!
关于qt - 在 QGraphicsView 上绘制一个矩形(或任何东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654266/