Reputation: 688
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?
Upvotes: 3
Views: 2695
Reputation: 121
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);
}
}
Upvotes: 0
Reputation: 8958
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.
Upvotes: 2
Reputation: 17946
This is what first comes to mind. It should work, although there may be a simpler way:
QPushButton
.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.)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.
Upvotes: 4