为什么我的 QGraphicsLine 在错误的地方

Why is my QGraphicsLine in the wrong place

我想画一条线连接两个圆(QGraphicsEllipseItem),但是我发现这样写并没有得到想要的结果。

    //they have been initialized to the correct place
    QGraphicsEllipseItem* nodeu;
    QGraphicsEllipseItem* nodev;

    this->addLine(nodeu->x(), nodeu->y(), nodev->x(), nodev->y());

执行这些代码的结果是只出现了两个圆圈,没有出现线条。 像这样

我的粗略推断是坐标变换的问题,但是就是解决不了
谢谢!

您应该先在 UI 中添加一个 QGraphicsView 或:

  QGraphicsView *graphicsView;
  QGridLayout *gridLayout;
  gridLayout = new QGridLayout(centralwidget);
  gridLayout->setSpacing(0);
  gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
  graphicsView = new QGraphicsView(centralwidget);
  graphicsView->setObjectName(QString::fromUtf8("graphicsView"));

  gridLayout->addWidget(graphicsView, 0, 0, 1, 1);

然后 :

    QGraphicsScene *_scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(_scene);
    ui->graphicsView->setRenderHints(QPainter::Antialiasing);

    QGraphicsEllipseItem *nodeu = new QGraphicsEllipseItem;
    nodeu->setRect(20, 10, 20, 20);

    _scene->addItem(nodeu);


    QGraphicsEllipseItem *nodev = new QGraphicsEllipseItem;
    nodev->setRect(80, 60, 20, 20);
    _scene->addItem(nodev);

    QGraphicsLineItem *_lineItem = new QGraphicsLineItem;

    _lineItem->setLine(nodeu->rect().x() + nodeu->rect().width() / 2.0, nodeu->rect().y() + nodeu->rect().height() / 2.0,
                       nodev->rect().x() + nodev->rect().width() / 2.0, nodev->rect().y() + nodev->rect().height() / 2.0);
    _scene->addItem(_lineItem);

这是输出: