开发者

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 u开发者_如何转开发se 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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜