c
cordsac28. November 2017 13:23

How can I resize QgraphicItem using mouse

qt, QGraphicItem, resize, Rectangle, c++

I asked question under this topic previously too,But this is slightly difference. I 'm following this tutorial these days,In that tutorial you drawn rectangle using mouse.So I tried to draw a rectangle when a button click.here is my sample code.


mainwindow.h

 private:
 QGraphicsRectItem *rect;

mainwindow.cpp

void MainWindow::on_btnCreate_clicked()
{
    //VERectangle *rectA = new VERectangle();
   // rect->setRect(20,20,100,100);*/
    rect = workplaceScene->addRect(20,20,100,100);
}

when I click the button, rectangle is generating properly,But it cannot resize. Sir,could you please explain me,how can I enable resize functionality to this rectangle too? and when I select this rectangle rectangleSetting.Ui isn't enable too.How can I solve this problems.

Thank you!!!
Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

5
Evgenii Legotckoi
  • 29. November 2017 16:46

Hello...

You just added common Rectangle (QGraphicsRectItem) via addRect method. You need add Custom Rectangle via addItem method.
Because in common way rectangle hasn`t methods for resizing.
    c
    • 30. November 2017 14:56

    Thank you very much sir,I did so and rectangle is crated and which can now able to resize.


    void Widget::on_btnAdd_clicked()
    {
        VERectangle *io = new VERectangle();
        io->setRect(10,10,100,200);
        workplaceScene->addItem(io);
    }
    But when I click the rectangle rectangleSettings is not visible.

    void MainWindow::selectNewItem(QGraphicsItem *item)
    {
        switch (item->type()) {
        case QGraphicsRectItem::Type: {
            VERectangle *rect = qgraphicsitem_cast<VERectangle *>(item);
            ui->rectangleSettings->newRectangle(rect);
            break;
        }
        default:
            break;
        }
    }
    
    why it happening so and,how can I solve this...
      Evgenii Legotckoi
      • 3. Dezember 2017 16:22

      In my example (Vector Editor) I used special method, which changes Configuration Widgets for Items on the Graphics Scene. When You select some items, you should invoke signal, by this signal you need to evaluate method for changing Configuration widget.


      Please see this method in my example.
      void MainWindow::checkSelection()
      {
          checkActionStates();
          switch (workplaceScene->selectedItems().length()) {
          case 0:
              ui->rectangleSettings->deselect();
              ui->polylineSettings->deselect();
              checkActionStates();
              ui->toolsWidget->setEnabled(true);
              break;
          case 1:
              switch (workplaceScene->selectedItems().at(0)->type()) {
              case QGraphicsRectItem::Type:{
                  ui->rectangleSettings->setVisible(true);
                  ui->polylineSettings->deselect();
                  ui->polylineSettings->setVisible(false);
                  break;
              }
              default: {
                  ui->rectangleSettings->deselect();
                  ui->rectangleSettings->setVisible(false);
                  ui->polylineSettings->setVisible(true);
                  break;
              }
              }
              checkActionStates();
              ui->toolsWidget->setEnabled(true);
              break;
          default:
              ui->rectangleSettings->deselect();
              ui->polylineSettings->deselect();
              ui->toolsWidget->setEnabled(false);
              break;
          }
      }
        c
        • 4. Dezember 2017 11:14
        rectangleSettings .UI not visible only when the rectangles create this way.But rectangleSettings .ui visible for way of your reactangle creation.In my project I did both ways to create rectangles.But rectangleSettings .ui not visible when I create rectangles like this way..

        void Widget::on_btnAdd_clicked()
        {
            VERectangle *io = new VERectangle();
            io->setRect(10,10,100,200);
            workplaceScene->addItem(io);
        }


          Evgenii Legotckoi
          • 4. Dezember 2017 16:06

          I forgot about another method.

          void MainWindow::checkActionStates()
          {
              ui->workplaceView->setDragMode(QGraphicsView::NoDrag);
              ui->rectangleSettings->setVisible(false);
              ui->polylineSettings->setVisible(false);
              switch (workplaceScene->currentAction()){
              case VEWorkplace::LineType:
                  ui->polylineSettings->setVisible(true);
                  break;
              case VEWorkplace::RectangleType:
                  ui->rectangleSettings->setVisible(true);
                  break;
              case VEWorkplace::SelectionType:
                  break;
              default:
                  ui->workplaceView->setDragMode(QGraphicsView::ScrollHandDrag);
                  break;
              }
          }
          I call this method, when I change state of graphics scene (in this case scene will be current action, create new item, or make selection). This method also changes visibility of settings widgets.

            Kommentare

            Nur autorisierte Benutzer können Kommentare posten.
            Bitte Anmelden oder Registrieren
            Letzte Kommentare
            A
            ALO1ZE19. Oktober 2024 08:19
            Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
            ИМ
            Игорь Максимов5. Oktober 2024 07:51
            Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
            d
            dblas55. Juli 2024 11:02
            QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
            k
            kmssr8. Februar 2024 18:43
            Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
            Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
            Jetzt im Forum diskutieren
            J
            JacobFib17. Oktober 2024 03:27
            добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
            JW
            Jhon Wick1. Oktober 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. September 2024 09:09
            Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
            F
            Fynjy22. Juli 2024 04:15
            при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

            Folgen Sie uns in sozialen Netzwerken