Search code examples
c++qtqgraphicsitemqgraphicslineitem

How to change QGraphicsLineItem programmatically


I'm working on resizeable and moveable overlay items, at the moment on a cross-hair. To make it resizeable I need to change parameters of my two QGraphicsLineItems, my cross-hair consists of. But calling the functions like setLength(), setP1(), setP2() or setLine() of the two lines do not show any effect. Please consider the following code:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsRectItem>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private:
  Ui::MainWindow    *ui;
  QGraphicsRectItem *_item;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
  ui->setupUi(this);

  QGraphicsScene *scene = new QGraphicsScene(this);
  _item                 = new QGraphicsRectItem(QRectF(0, 0, 100, 100));
  _item->setFlag(QGraphicsItem::ItemIsMovable);
  _item->setPen(QColor(102, 102, 102));

  auto l1 = new QGraphicsLineItem(0, 50, 100, 50, _item);
  auto l2 = new QGraphicsLineItem(50, 0, 50, 100, _item);

  l1->setPen(QColor(10, 255, 10));
  l2->setPen(QColor(10, 255, 10));

  scene->addItem(_item);

  ui->graphicsView->setScene(scene);
  ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft);

  ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

  // make lines longer by 10 on button press
  connect(ui->resize, &QPushButton::clicked, this, [this]() {
    auto childs = _item->childItems();
    if (childs.size() > 0)
    {
      auto line1 = dynamic_cast<QGraphicsLineItem *>(childs.at(0));
      auto line2 = dynamic_cast<QGraphicsLineItem *>(childs.at(1));
      line1->line().setLine(0, 55, 110, 55); //no effect
      line2->line().setLine(55, 0, 55, 110); //no effect
    }
  });
}

MainWindow::~MainWindow() { delete ui; }

Because I need to handle mousePressEvent, mouseMoveEvent also, I stopped to go with QGraphicsItemGroup.

Thank you in advance.


Solution

  • Use QGraphicsLineItem::setLine instead:

    //...
    line1->setLine(0, 55, 110, 55);
    line2->setLine(55, 0, 55, 110);