c
cordsacOct. 23, 2017, 11: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, 12:35 p.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. 26, 2017, 2:34 a.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, 5:14 p.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
        Ua

        Qt - Test 001. Signals and slots

        • Result:84points,
        • Rating points4
        Ua

        Qt - Test 001. Signals and slots

        • Result:42points,
        • Rating points-8
        ОК

        Qt - Test 001. Signals and slots

        • Result:47points,
        • Rating points-6
        Last comments
        ИМ
        Игорь МаксимовNov. 22, 2024, 9:51 p.m.
        Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
        Evgenii Legotckoi
        Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
        Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
        A
        ALO1ZEOct. 19, 2024, 5:19 p.m.
        Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
        ИМ
        Игорь МаксимовOct. 5, 2024, 4:51 p.m.
        Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
        d
        dblas5July 5, 2024, 8:02 p.m.
        QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
        Now discuss on the forum
        f
        firstlunoxodFeb. 15, 2025, 1:46 p.m.
        Рисование на QGraphicsScene при зажатой кнопке мыши Подскажите, пожалуйста! Как данный класс можно дополнить, чтобы созданные объекты можно было перемещать мышкой по сцене?
        Дмитрий
        ДмитрийFeb. 3, 2025, 4:24 p.m.
        Создание deb-пакета. Как создать ярлык на рабочем столе после установки собственного deb-пакета? Всем привет. Сделал свой deb-пакет с программой. Всё устанавливается и работает. Ставлю по пути /usr/bin/my_application. Как для пользователя при установке пакета сразу создать ярлык на раб…
        NW
        Nayo WaiJan. 30, 2025, 7:22 p.m.
        не запускается компьютер!!! Не запускается компьютер (точнее работает блок , но сам монитор вообще жесть)В общем я ничего с интернета не скачивала в последнее время. На компе никаких левых пр…
        n
        nklyJan. 3, 2025, 12:52 p.m.
        Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
        M
        MarselAug. 17, 2023, 12:26 a.m.
        OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.

        Follow us in social networks