How to Create QGraphicsItem(Lines, Rectangles, etc.) in QGraphicsScence by mouse?
-
@darrenleeleelee1
Yes. It's not that Qt does that for you, it's that you write the code. You know how to act on a mouse down or click or whatever. You know how to create a newQGraphicsItem
and add it to the scene. So, for example, when the mouse is downed or clicked you could get its position, create a graphics item, and set its position to the mouse coordinates.In that example I referred you to, for instance, there is:
The mousePressEvent() function handles mouse press event's different depending on which mode the DiagramScene is in. We examine its implementation for each mode:
void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { if (mouseEvent->button() != Qt::LeftButton) return; DiagramItem *item; switch (myMode) { case InsertItem: item = new DiagramItem(myItemType, myItemMenu); item->setBrush(myItemColor); addItem(item); item->setPos(mouseEvent->scenePos()); emit itemInserted(item); break;
We simply create a new DiagramItem and add it to the scene at the position the mouse was pressed. Note that the origin of its local coordinate system will be under the mouse pointer position.
-
@darrenleeleelee1
If you want to create those "freehand" letter drawings as aGraphicsItem
you would have to add it as aQGraphicsPathItem
composed from a multi-itemQPainterPath
. Unless you are prepared to do it as aQGraphicsPixmapItem
, and lose the ability to manipulate the points.It probably doesn't matter which of
QGraphicsScence
orQGraphicsView
to catch the mouse event, so long as it works. I did refer you to the DiagramScene example which seems to use the scene's mouse event. -
@darrenleeleelee1
You might get some clues from https://doc.qt.io/qt-5/qtwidgets-widgets-scribble-example.html in combination with https://forum.qt.io/topic/94586/draw-line-on-mouse-click & https://forum.qt.io/topic/94622/need-help-with-qgraphicsitem-painter . -
@darrenleeleelee1
I don't know what to say, it's just code you need to write. Note where the mouse goes down, note where the mouse is released and at that stage create aQGraphicsLineItem
or whatever between those two points. -
@darrenleeleelee1 said in How to Create QGraphicsItem(Lines, Rectangles, etc.) in QGraphicsScence by mouse?:
But if I create the QGraphicsLineItem at mousedReleasd, when I holding the mouse pressed
How can you get mouse released event if you hold mouse button pressed? Can you please explain better?
-
@jsulm I am thinking if I can change the existing QGraphicsLineItem to keep update to where my mouse position, and the start position is the moused click position.But I don't know how to adjust existing QGraphicsLineItem.
-
@darrenleeleelee1 said in How to Create QGraphicsItem(Lines, Rectangles, etc.) in QGraphicsScence by mouse?:
But I don't know how to adjust existing QGraphicsLineItem.
Again, I don't know what to say. You have
QGraphicsLineItem::setLine()
. I don't see the problems you see.