Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene

QGraphicsItem, QPainter, QPolygon, Qt, Qt5, Рисование Qt, Рисование Qt5, треугольник

Drawing interfaces, the formation of the database tables, work with the network - it's all good, but sometimes you want to just draw something, such as a triangle. And then of course, revive this place, so that they can be controlled, and subsequently to turn this project into a little game. Well, who does not want to write your own game, even the most simple?

Let us then take the first step toward the unpretentious games, namely deal with drawing objects to Qt, trying to draw a triangle.

Project structure

  • Triangle.pro - Project profile, created by default, and in this project does not require the correction;
  • main.cpp - file, which starts with the application, the file is called a widget, which will be located in the graphic scene with a triangle;
  • widget.h - header file of a widget with a graphic scene;
  • widget.cpp - source file of widget;
  • triangle.h - Triangle header file class that inherits from QGraphicsItem;
  • triangle.cpp - source file of Triangle class;

mainwindow.ui

The interface design simply throws QGraphicsView in the widget. Nothing more is required.

widget.h

This file is only for defining a graphical scene and the triangle object with which we work.

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QGraphicsScene>

#include <triangle.h>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget      *ui;
    QGraphicsScene  *scene;    
    Triangle        *triangle;  
};

#endif // WIDGET_H

widget.cpp

In this file are configured objects QGraphicsView, QGraphicsScene , and the triangle object is created and installed on the graphic scene.

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->resize(600,600);          // Set sizes of widget
    this->setFixedSize(600,600);    // Fix sizes of widget
    scene = new QGraphicsScene();   // Init graphic scene
    triangle = new Triangle();      // Init Triangle

    ui->graphicsView->setScene(scene);  // Set graphics scene into graphicsView
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);    
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 

    scene->setSceneRect(-250,-250,500,500); 

    scene->addLine(-250,0,250,0,QPen(Qt::black));   // Add horizontal line via center
    scene->addLine(0,-250,0,250,QPen(Qt::black));   // Add vertical line via center

    scene->addItem(triangle);   
    triangle->setPos(0,0);      


}

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

triangle.h

But now is the time to work out the class itself, which creates a triangle. In this case, we are inheriting from QGraphicsItem .

#ifndef TRIANGLE_H
#define TRIANGLE_H

#include <QGraphicsItem>
#include <QPainter>

// Наследуемся от QGraphicsItem
class Triangle : public QGraphicsItem
{
public:
    Triangle();
    ~Triangle();

protected:
    QRectF boundingRect() const;    /* We define a virtual method that returns the area in which the triangle is
                                     * */
    /* Define a method for rendering a triangle
     * */
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
};

#endif // TRIANGLE_H

triangle.cpp

Now draw a triangle in our class. Here, there is one important moment. Coordinate System QGraphicsItem object - a concept different from the coordinate system of the graphic scenes. That is, each QGraphicsItem object or inherited from this class has its own coordinate system, which is translated in QGraphicsScene coordinate system. When we assign a position where there will be an object in the graphic scene, we indicate where it will be located point of the graphic object that has the coordinates 0 on the X-axis and 0 on the Y-axis in the coordinate system of the object, so it is important that this point was the center of the graphic. This will facilitate further work, unless of course you are not consciously intend to other options.

#include "triangle.h"

Triangle::Triangle() :
    QGraphicsItem()
{

}

Triangle::~Triangle()
{

}

QRectF Triangle::boundingRect() const
{
    return QRectF(-25,-40,50,80);   // We are limiting the area of triangle
}

void Triangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
        QPolygon polygon;   // Using Polygon class, to draw the triangle
        // We put the coordinates of points in the polygonal model
        polygon << QPoint(0,-40) << QPoint(25,40) << QPoint(-25,40);
        painter->setBrush(Qt::red);     // We set the brush, which will render the object
        painter->drawPolygon(polygon);  // Draw a triangle on a polygonal model
        Q_UNUSED(option);
        Q_UNUSED(widget);
}

Result

As a result, you should get an application that displays a red triangle in the center of the graphic scenes at the intersection of the two lines, as shown in the figure.

Download project

Video

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
TT
June 13, 2019, 7:01 p.m.
Taimoor Tanweer

C++ - Test 001. The first program and data types

  • Result:66points,
  • Rating points-1
TT
June 13, 2019, 6:51 p.m.
Taimoor Tanweer

C++ - Test 002. Constants

  • Result:75points,
  • Rating points2
ВМ
June 13, 2019, 12:30 p.m.
Ваня Мороз

C++ - Test 001. The first program and data types

  • Result:100points,
  • Rating points10
Last comments
i
June 17, 2019, 6:10 a.m.
ingenfly

Только по осям xAxis2, уAxis2 значения начинаются с 0. Почему-то xAxis2 и xAxis не синхронизированы по данным. Ну и QCustomPlot последний.
June 16, 2019, 8:21 p.m.
Евгений Легоцкой

Добрый день. Ну точно также добавляете ту же самую информацию на ось xAxis2, только добавляете другое форматирование customPlot->xAxis2->setDateTimeFormat("hh:mm"); если я ...
EF
June 14, 2019, 1:56 p.m.
Egor Fomin

Спасибо за ваш ответ, у меня получилось реализовать это. Тем не менее появилась другая проблема, поэтому опять надеюсь на вашу помощь. Скажем, я уже выставил точки и они соеденены. Когда я нач...
d
June 13, 2019, 2:47 p.m.
damix

Можно классу, который описывает точку, добавить сигнал, который подавать (emit), когда точка перемещается (переопределить mouseMoveEvent или mouseReleaseEvent). Так вот эти сигналы у каждой из...
i
June 13, 2019, 2:09 p.m.
ingenfly

Здравствайте! Подскажите, пожалуйста: customPlot->xAxis2->setTickLabels(true); //Здесь включается отображение данных на оси xAxis2. а можно как-то продублировать информацию cus...
Now discuss on the forum
June 20, 2019, 9:30 a.m.
IscanderChe

Вернулся к этой задачке только-только, поэтому и не ответил ничего раньше.Как переопределить mouseReleaseEvent(QMouseEvent* event) у QTableView, если QTableView задан в ui? Или задавать QTabl...
I
June 19, 2019, 1:41 p.m.
Intruder

Всем добрый день. При разборе XML файла наткнулся на тег вот такого плана: <TagName attribute1="value1" attribute2="value2" /> При попытке проверить на наличие такого элеме...
June 19, 2019, 12:55 p.m.
Михаиллл

Скажите пожалуйста, как его в таком случае перемещать и удалять?
June 18, 2019, 7:50 p.m.
Дмитрий

Большое спасибо! SDK заработал.К сожалению удалось продвинутся только на один шаг. При сборке чистого проекта NDK выдаёт следующие ошибки C:\Android\ndk-bundle/toolchains/arm-linux-andr...
June 18, 2019, 4:59 p.m.
Михаиллл

Добрый день.В этом учебнике представлен код INSTALLED_APPS = ( ... 'rest_framework', 'snippets.apps.SnippetsConfig',) На строчке 'snippets.apps.SnippetsConf...
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB