c
cordsac23 октября 2017 г. 13:18

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);
}
Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Вам это нравится? Поделитесь в социальных сетях!

3
Evgenii Legotckoi
  • 24 октября 2017 г. 2:35
  • (ред.)

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
    • 25 октября 2017 г. 16:34

    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
      • 28 октября 2017 г. 7:14

      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.

        Комментарии

        Только авторизованные пользователи могут публиковать комментарии.
        Пожалуйста, авторизуйтесь или зарегистрируйтесь
        d
        • dsfs
        • 26 апреля 2024 г. 14:56

        C++ - Тест 004. Указатели, Массивы и Циклы

        • Результат:80баллов,
        • Очки рейтинга4
        d
        • dsfs
        • 26 апреля 2024 г. 14:45

        C++ - Тест 002. Константы

        • Результат:50баллов,
        • Очки рейтинга-4
        d
        • dsfs
        • 26 апреля 2024 г. 14:35

        C++ - Тест 001. Первая программа и типы данных

        • Результат:73баллов,
        • Очки рейтинга1
        Последние комментарии
        k
        kmssr9 февраля 2024 г. 5:43
        Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
        АК
        Анатолий Кононенко5 февраля 2024 г. 12:50
        Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
        EVA
        EVA25 декабря 2023 г. 21:30
        Boost - статическая линковка в CMake проекте под Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
        J
        JonnyJo25 декабря 2023 г. 19:38
        Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
        G
        Gvozdik19 декабря 2023 г. 8:01
        Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
        Сейчас обсуждают на форуме
        IscanderChe
        IscanderChe30 апреля 2024 г. 14:22
        Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…
        G
        Gar22 апреля 2024 г. 15:46
        Clipboard Как скопировать окно целиком в clipb?
        DA
        Dr Gangil Academics20 апреля 2024 г. 17:45
        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_vlasov14 апреля 2024 г. 16:41
        Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
        Павел Дорофеев
        Павел Дорофеев14 апреля 2024 г. 12:35
        QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь

        Следите за нами в социальных сетях