c
cordsacOct. 23, 2017, 1:18 p.m.

How can I re-size the graphicviewitem using mouse

How can I change the QGraphicView Item size using mouse.In this tutorial have that function to change the size using mouse,but I'm not understand that.Can you explain how resize the rectangle size using mouse.this code generate the 2 rectangles,how can I change the sizes of those rectangles.I also have a question how line item  create,resize,move and rotate in this tutorial .


#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    scene = new QGraphicsScene();
    ui->graphicsView->setScene(scene);
    scene->setSceneRect(0,0,400,400);
 
    // Create the first red rectangle on the graphic scene
    QGraphicsRectItem *rect1 = new QGraphicsRectItem();
    rect1->setRect(10,50,100,50);
    rect1->setBrush(QBrush(Qt::red));
    rect1->setPen(QPen(QBrush(Qt::black),2));
    scene->addItem(rect1);
 
    // And create a second blue rectangle on the graphic scene
    QGraphicsRectItem *rect2 = new QGraphicsRectItem();
    rect2->setRect(150,100,115,75);
    rect2->setBrush(QBrush(Qt::blue));
    rect2->setPen(QPen(QBrush(Qt::black),2));
    scene->addItem(rect2);
}
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!

3
Evgenii Legotckoi
  • Oct. 24, 2017, 2:35 a.m.
  • (edited)

First, You need inherit from QGraphicsRectItem and override methods mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent().

You need to understand, how Qt works, and how to work with QGraphicsRectItem, QGraphicsView, QGraphicsScene.
I don`t see reasons to write full code for you. Therefore I will explain main moments and will give you direction to learning.

You can learn inhertence from QGraphicsItem in this article .
Just make moving of QGraphicsItem without Flag ItemIsMovable. Try to do it.
After that, you can make field in QGraphicsItem for resizing.
    c
    • Oct. 25, 2017, 4:34 p.m.

    sir,can you explain how this this line item generate when button click and,how rotate,move and resize it using mouse.which classes are related to line functions. I create and re-size the rectangles in this way(I uploaded my sample project here) , now I need to generate line Item when button click and,need to resize,move and rotate like your tutorial.please check my sample project and if you can please edit and give me a solution please.


    Thank you!!!
      Evgenii Legotckoi
      • Oct. 28, 2017, 7:14 a.m.

      For Line You need create another class which will be inherited from QGraphicsPathItem. And I think, You should use special enum for types of Line or Rectangle.

      When You click btn Rectangle or Line, You will set variable, which contains type of current item, with which You work now.
      When You work with some item, You need to store pointer to this Item, now You use rect.
      But You can you pointer to base class QGraphicsItem for Line or Rectangle. Is it possible.
      In my project in article Yu can see variable currentItem .

      First, try to make using pointer to base class for Lines and Rectangles.

        Comments

        Only authorized users can post comments.
        Please, Log in or Sign up
        d
        • dsfs
        • April 26, 2024, 2:56 p.m.

        C ++ - Test 004. Pointers, Arrays and Loops

        • Result:80points,
        • Rating points4
        d
        • dsfs
        • April 26, 2024, 2:45 p.m.

        C++ - Test 002. Constants

        • Result:50points,
        • Rating points-4
        d
        • dsfs
        • April 26, 2024, 2:35 p.m.

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

        • Result:73points,
        • Rating points1
        Last comments
        k
        kmssrFeb. 9, 2024, 5:43 a.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, 9:30 p.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, 7:38 p.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. 19, 2023, 8:01 a.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
        Evgenii Legotckoi
        Evgenii LegotckoiMay 3, 2024, 12:07 a.m.
        Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
        IscanderChe
        IscanderCheApril 30, 2024, 2:22 p.m.
        Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…
        G
        GarApril 22, 2024, 3:46 p.m.
        Clipboard Как скопировать окно целиком в clipb?
        Павел Дорофеев
        Павел ДорофеевApril 14, 2024, 12:35 p.m.
        QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
        f
        fastrexApril 4, 2024, 2:47 p.m.
        Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

        Follow us in social networks