Evgenii Legotckoi
Evgenii LegotckoiSept. 17, 2015, 10:22 a.m.

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

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

J
  • June 8, 2023, 12:14 p.m.
  • (edited)

Евгений, здравствуйте!
Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация, ни доп.литература не помогла.
Проблема, собственно, в следующем. Когда я делаю графическую форму, компоную графические слои и виджеты, я получаю размеры.

Справа мы видим координаты graphicView

Дальше берём сам код:

this->resize(10000,10000);          // Задаем размеры виджета, то есть окна
this->setFixedSize(460,380);    // Фиксируем размеры виджета

в первой строке мы задаём размеры виджета, но если их поменять, то сам его размер не изменяется, а изменения происходят, если поменять нижнюю строчку. Почему так?

Получается вот так:
1 -это сам виджет, 2 - это наш слой. И оба они имеют свои размеры как на предыдущей картинке.

Вот так она окно выглядит при изменении второй строчки

    scene->setSceneRect(-250,-250,700,700); // Устанавливаем область графической сцены

    map->setPos(0,0);      // Устанавливаем квадрат в центр сцены

Далее вот эти строчки:
Изменяя размеры в scene->setSceneRect(), визуально ничего не меняется. Почему?
Это и есть установка размеров области нашего QGraphicsView? Если да- то что за размеры остаются в ui-файле при этом?

Далее, я пытаюсь отрисовать квадрат в классе Map, но он не появляется на сцене, хотя когда я делал на координатах вашего урока, он был. Но как только я начал изменять их, он исчез. И тут я задумался собственно. Я хотел нарисовать квадрат ровно в левом углу сцены, которая имеет координаты (-250,-250), но квадрат так и не появлялся. Только когда я ставил координаты где-то ориенитирочно(-130,-130), то он вставал как раз в левый угол


Еще, я так и не понял что делает функция

QRectF Map::boundingRect() const
{
    return QRectF(0,0,60,60);   // Ограничиваем область, в которой лежит прямоугольник
}

Что именно она ограничивает? Думал, что за границы, которые определяет этот метод, нельзя "выйти", т.е, отрисовать квадрат "ЗА" установленными этим методом координатами, но это не так!
В итоге решил поиграться с координатами в графическом файлу ui и квадрат после этого совсем исчез.
Подскажите, что я делаю не так? В чём моя основная ошибка? Может где-то можно об этом почитать поподробнее? Я помню ваши слова, что координаты QGraphicsScene и QGraphicsItem разные, но я всё равно не понимаю как автоматически управлять этими вещами. Например, если я хочу нарисовать сцену и отрисовать на ней квадраты с помощью цикла (к примеру, как в игре "Морской бой"). Мы же должна хорошо понимать и знать координаты сцены и самого объекта отрисовки. Особенно, координаты углов самого объекта.
Заранее благодарю за ответ, Евгений!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 11:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 7:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 5:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 6:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 2:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 4:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 3:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 13, 2024, 11:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 1:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks