c
cordsacҚаз. 23, 2017, 1: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, 4: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.

        Пікірлер

        Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
        Кіріңіз немесе Тіркеліңіз
        Г

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

        • Нәтиже:66ұпай,
        • Бағалау ұпайлары-1
        t

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

        • Нәтиже:33ұпай,
        • Бағалау ұпайлары-10
        t

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

        • Нәтиже:52ұпай,
        • Бағалау ұпайлары-4
        Соңғы пікірлер
        G
        GoattRockҚыр. 3, 2024, 1:50 Т.Қ.
        Linux жүйесінде файлдарды қалай көшіруге болады Задумывались когда-нибудь о том, как мы привыкли доверять свои вещи службам грузоперевозок? Сейчас такие услуги стали неотъемлемой частью нашей жизни, особенно когда речь идет о переездах между …
        d
        dblas5Шілде 5, 2024, 11:02 Т.Ж.
        QML - Сабақ 016. SQLite деректер қоры және онымен QML Qt-та жұмыс істеу Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
        k
        kmssrАқп. 8, 2024, 6:43 Т.Қ.
        Qt Linux - Сабақ 001. Linux астында Autorun Qt қолданбасы как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
        АК
        Анатолий КононенкоАқп. 5, 2024, 1:50 Т.Ж.
        Qt WinAPI - Сабақ 007. Qt ішінде ICMP Ping арқылы жұмыс істеу Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
        Енді форумда талқылаңыз
        Evgenii Legotckoi
        Evgenii LegotckoiМаусым 24, 2024, 3:11 Т.Қ.
        добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
        F
        FynjyШілде 22, 2024, 4:15 Т.Ж.
        при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
        BlinCT
        BlinCTМаусым 25, 2024, 1 Т.Ж.
        Нарисовать кривую в qml Всем привет. Имеется Лист листов с тосками, точки получаны интерполяцией Лагранжа. Вопрос, как этими точками нарисовать кривую? ChartView отпадает сразу, в qt6.7 появился новый элемент…
        BlinCT
        BlinCTМамыр 5, 2024, 5:46 Т.Ж.
        Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
        Evgenii Legotckoi
        Evgenii LegotckoiМамыр 2, 2024, 2:07 Т.Қ.
        Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.

        Бізді әлеуметтік желілерде бақылаңыз