Get object clicked by mouseEvent in Qt C++ - c++

I have a scene made up of objects, each with a different position. I also have 2–4 pawns I'd like to move to the position of the object clicked, not to the position of the event.
I tried doing something like event->pos() but that gives me the coordinates of the event. Is there any way to do this?

The method you're looking for is QGraphicsView::items().

Related

Qt: Custom QGraphicsItem not showing when boundingRect() center is out of view

I'm making a Diagram (Fluxogram) program and for days I'm stuck with this issue:
I have a custom QGraphicsScene that expands horizontally whenever I place an item to it's rightmost area. The problem is that my custom arrows (they inherit QGraphicsPathItem) disappear from the scene whenever it's boundingRect() center is scrolled off the view. Everytime the scene expands, both it's sceneRect() and the view's sceneRect() are updated as well.
I've:
set ui->graphicsView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate)
the item flags QGraphicsItem::ItemIgnoresTransformations and QGraphicsItem::ItemSendsGeometryChanges, setActive(true) on the item as well, and everytime I add an arrow to the scene i call the update(sceneRect()) method. Still, everytime I scroll the view, as soon as the arrow's boundingRect() center moves away from the view, all the arrow disappears. If I scroll back and the boundingRect() center enters the view, all the arrow appears again.
Can someone give me a tip of what I might be missing? I've been using Qt's example project diagramscene as reference, so a lot of my code is similar (the "press item toolButton -> click on the scene" relation to insert items, the way they place the arrows to connect the objects,...).
In the meanwhile I'll try to make a minimal running example that can show what my issue is.
Your Arrow object inherits from QGraphicsPathItem, which I expect also implements the QGraphicsItem::shape function.
Override the shape function in your Arrow class, to return the shape of the item. This, along with the boundingRect is used to collision detection and detection of an item on-screen.
In addition, before changing the shape of an item by changing its boundingRect, you need to call prepareGeometryChange.
As the docs state: -
Prepares the item for a geometry change. Call this function before changing the bounding rect of an item to keep QGraphicsScene's index up to date.
So, in the Arrow class, store a QRectF called m_boundingRect and in the constructor: -
prepareGeometryChange();
m_boundingRect = QRectF(-x, -y, x*2, y*2);
Then return m_boundingRect in the boundingRect() function.
If this is still an issue, I expect it's something in QGraphicsPainterPath that's causing the problem, in which case, you can simply inherit from QGraphicsItem and store a QPainterPath with which you draw in the item's paint function and also return the painter path in shape().
You are making your life too complicated. Do not subclass QGraphicsPathItem just use it and update its path value every time position of anchors (from to) changes.

Qt C++ Let multiple QGraphicsItem handle one mouse event

I've created an object Chartblock that implements QGraphicsItem. My goal is to create a grid of these objects, and when the mouse button is pressed (and held) and is drug over each block, perform something on each block as the cursor enters it.
Since a QGraphicsItem grabs the mouse events when it is clicked within it, other Items will not fire for the mouseMoveEvent. I then created an object based on the QGraphicsItemGroup to handle all the mouse events, but then I would need some way to pass mousePressEvent/mouseReleaseEvent as well as mouseMoveEvent to each child that the cursor is over.
Am I overthinking how to do this? It seems like such a simple action shouldn't be that difficult to create, but with QGraphicsItems holding onto the mouse events for itself, I'm not sure how to get around it. I've read similar situations, but nothing seems to give a straightforward answer.
Edit: I suppose a way to do this would keep track of the coordinates/sizes of every single QGraphicsItem I create in an array, then get the position of the cursor in the Group mouseMoveEvent, and see if there's a hit..
I was able to pull together a few similar answers to create a solution; I dropped the idea of placing all my QGraphicItem's in a Group, and placed them directly on a scene. With the scene grabbing all mouse events, I have the mouseMoveEvent check to see if the current position is on top of a QGraphicsItem - if so, perform something.
I still need to try and get itemAt() to work for my own classes that implement QGraphicsItem, as itemAt returns only QGraphicsItem's, but I'm sure some cast should get it working.
void ChartScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QPointF mousePosition = event->scenePos();
QGraphicsItem* pItem = this->itemAt(mousePosition.x(), mousePosition.y());
}

Accessing the the coordinates in a QPushbutton clicked slot

I have a QPushButton with an image that has two areas that I want to handle differently when clicked. Due to the positioning on the image, I cannot really use separate buttons for the two images.
What I'd like to do is, in the slot where I am handling the click, have it check the coordinates of the click to determine which area was clicked.
Is there a way to access this?
This is what first comes to mind. It should work, although there may be a simpler way:
Create your own class that derives from QPushButton.
Override the necessary mouse events (mousePressEvent and mouseReleaseEvent) and, before calling the base class implementation, set a property in your object using setProperty with the position of the mouse click. (The position is available from the event parameter.)
In the slot handling the event, use sender() to get the button, and read the property using property().
If you don't need to treat your object as the base class (QPushButton*) you could just create a new signal that includes the mouse event and attach that to your slot. Then you wouldn't need the property at all.
You can get the current mouse position using QCursor::pos() which returns the position of the cursor (hot spot) in global screen coordinates.
Now screen coordinates are not easy to use, and probably not what you want. Luckily there is a way to transform screen coordinates to coordinates relative to a widget.
QPoint _Position = _Button->mapFromGlobal(QCursor::pos());
This should tell you where on the button the mouse was when the user clicked. And you can take it from there.
Building on #Liz's simple mechanism, here's what I did; this is in a slot method that is called on pressed() but generalizes to other situations. Note that using pushButton->geometry() gives you coordinates that are already in global space so you don't need to mapFromGlobal.
void MainWindow::handlePlanButtonPress()
{
int clickX = QCursor::pos().x();
int middle = m_buttonPlan->geometry().center().x();
if ( clickX < middle ) {
// left half of button was pressed
m_buttonPlan->setStyleSheet(sStyleLargeBlueLeft);
} else {
// right half of button was pressed
m_buttonPlan->setStyleSheet(sStyleLargeBlueRight);
}
}

Finding current mouse position in QT

This is my first attempt at writing a QT app, and I'm just trying to get a feel for how it works. My goal is to have a 400x400 widget which knows the exact position of the mouse when the mouse is hovering over it. For example, if the mouse was hovering in the top left corner, the position might be 10,10 (or something similar). If the mouse is in the bottom right corner, it might say 390,390.
Eventually, these coordinates will be displayed in a label on the main window, but that should be trivial. I'm stuck at the actual fetching of the coordinates. Any ideas?
For your widget, you must enable mouse tracking.
Then, you can either install an event filter, paying attention to mouse events and looking for the move event, or you can inherit from QWidget and override the mouse event, looking for mouse move events.
http://doc.qt.io/qt-4.8/qwidget.html#mouseTracking-prop
http://doc.qt.io/qt-4.8/eventsandfilters.html
http://doc.qt.io/qt-4.8/qmouseevent.html
If you are ever in a situation when you don't need actual tracking, just position at the moment, you can use QCursor::pos().

Get relative X/Y of a mouse-click on a MFC CListBox item

I have a CListBox with custom drawing being used, and need to detect mouse-clicks within each item to perform actions.
I can listen for mouse-clicks on the main control and mess about translating coords into the local space of the RECT for the item under the mouse. But is it possible to register message handlers for clicks on individual list items... are there messages for that?
You can use the LVM_HITTEST message to find out which item was clicked.
Well you could just listen for the LBN_SELCHANGE notification. This will fire every time the user clicks a new item. It won't activate if the already selected item is selected though. This may, or may not, be a problem.
Beyond that I'm pretty sure you'll need to intercept WM_LBUTTONUP messages and transform them to the list box's client space ...
OR You could just use a single columned CListCtrl (ListView) class with headers turned off (LVS_NOCOLUMNHEADER). You can then trap the NM_CLICK message. Personally, I massively prefer CListCtrl to CListBox. It IS a little more complex but way more powerful :)
Edit: Or you could try using http://msdn.microsoft.com/en-us/library/bb761323(VS.85).aspx
I'm not certain I understand why you need to have the XY coordinate inside each item of a Clistbox ?
anyway,
AFAIK, Individual items are not CWnd derived objects.
You could get the mouse position inside the control with OnLButtonDown (or up), it returns a CPoint.
After that, use CListBox::GetItemRect to get the rect of the currently selected item, do a bit of pixel computation and you should be able to get the XY inside the rect of the selected item.
Max.
Use the DPtoLP function to convert device coordinates into logical coordinates.
http://msdn.microsoft.com/en-us/library/dd162474(v=vs.85).aspx