Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

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

  • - 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;


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


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

    explicit Widget(QWidget *parent = 0);

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

#endif // WIDGET_H


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) :
    ui(new Ui::Widget)
    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


    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



    delete ui;


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

    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


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() :




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


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



Only authorized users can post comments.
Please, Log in or Sign up
Last comments
Feb. 21, 2019, 12:51 p.m.
Евгений Легоцкой

Иногда CMake приходится перезапускать начисто, не обновляет кэш
Feb. 21, 2019, 12:29 p.m.

Я указал данные строки, т.к. без них у меня вылетала следующая ошибка: By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configurat...
Feb. 21, 2019, 12:08 p.m.

Вот атк выглядит мой проектник, посмотрите его. cmake_minimum_required(VERSION 3.6)project(projecttimer)set(CMAKE_CXX_STANDARD 11)set(CMAKE_AUTOMOC ON)set(CMAKE_AUTORCC ON)find_packa...
Feb. 21, 2019, 12:04 p.m.

Смотрите, если вы используете глобально для проекта -DCMAKE_PREFIX_PATH= то вам не надо уже указывать вот эти строкиset(Qt5Core_DIR "C:/Qt/5.12.1/mingw73_64/lib/cmake/Qt5Core")set(Qt5Gui_DIR...
Feb. 21, 2019, 11:54 a.m.

Даже не запускается. main.cpp у меня точно такой же, как в статье. CMakeLists.txt пришлось немного подправить (прикрепил ниже), т.к. не находились некоторые файлы. cmake_minimum_requi...
Now discuss on the forum
Feb. 21, 2019, 8:58 a.m.
Евгений Легоцкой

Ну у меня координаты передавались в зависимости от положения курсора мыши, а в вам по сути нужно будет аналогичным способом посылать даннные из полей ввода. Так что здесь скорее интерфес...
Feb. 20, 2019, 9:55 p.m.
Евгений Легоцкой

Не до конца понимаю сути вопроса, наверное, нужно увидеть программный код и попытку его применения, но к методам базового класса можно обращаться в наследованном классе через вызов по имени ба...
Feb. 20, 2019, 3:06 p.m.
Maciej Urmański

Yes, ok I have solution! Thank you for directing me about annotate.:) Solution is: users_in = User.objects.filter(joined_users__goal=goal, joined_users__joined=True)
Feb. 20, 2019, 2:40 p.m.
Евгений Легоцкой

Думаю, что ещё можно переопределить mouseReleaseEvent(QMouseEvent* event) у QTableView, который содержит модель и немного поиграться с индексом. Если это индекс, который соответству...
Feb. 20, 2019, 10:34 a.m.
Евгений Легоцкой

Да, так тоже можно. Единственный момент в том, что lupdate не всегда понимает, к какому контексту это дело относится, и может запихать в левый контекст. В небольшом проекте это не критич...
Join us in social networks

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