I want to draw a line to connect two circles (QGraphicsEllipseItem), but I find that I don't get the desired result with this way of writing.
//they have been initialized to the correct place
QGraphicsEllipseItem* nodeu;
QGraphicsEllipseItem* nodev;
this->addLine(nodeu->x(), nodeu->y(), nodev->x(), nodev->y());
The result of executing these codes is that only two circles appear, but no lines appear. like this
My rough inference is the problem of coordinate transformation, but I just can't solve it.
thank you!
CodePudding user response:
you should first add one QGraphicsView
in your UI or :
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);
then :
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);
this is the output: