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 р. 02: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 р. 07: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.

        Коментарі

        Only authorized users can post comments.
        Please, Log in or Sign up
        sf

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

        • Результат:90бали,
        • Рейтинг балів8
        МВ

        Qt - Тест 001. Сигналы и слоты

        • Результат:68бали,
        • Рейтинг балів-1
        ЛС

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

        • Результат:53бали,
        • Рейтинг балів-4
        Останні коментарі
        A
        ALO1ZE19 жовтня 2024 р. 08:19
        Читалка файлів fb3 на Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
        ИМ
        Игорь Максимов05 жовтня 2024 р. 07:51
        Django - Урок 064. Як написати розширення для Python Markdown Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
        d
        dblas505 липня 2024 р. 11:02
        QML - Урок 016. База даних SQLite та робота з нею в QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
        k
        kmssr08 лютого 2024 р. 18:43
        Qt Linux - Урок 001. Автозапуск програми Qt під Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
        АК
        Анатолий Кононенко05 лютого 2024 р. 01:50
        Qt WinAPI - Урок 007. Робота з ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
        Тепер обговоріть на форумі
        J
        JacobFib17 жовтня 2024 р. 03:27
        добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
        ИМ
        Игорь Максимов03 жовтня 2024 р. 04:05
        Реализация навигации по разделам Спасибо Евгений!
        JW
        Jhon Wick01 жовтня 2024 р. 15:52
        Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
        КГ
        Кирилл Гусарев27 вересня 2024 р. 09:09
        Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
        F
        Fynjy22 липня 2024 р. 04:15
        при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

        Слідкуйте за нами в соціальних мережах