[英]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.我有一个带有图像的 QPushButton,该图像具有两个我想在单击时以不同方式处理的区域。 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:它应该可以工作,尽管可能有更简单的方法:
QPushButton
.创建您自己的派生自QPushButton
的 class 。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.覆盖必要的鼠标事件( mousePressEvent
和mouseReleaseEvent
),并在调用基本 class 实现之前,使用setProperty
和鼠标单击的 Z4757FE07FD492A8BE0EA6A760D683D6E 在 object 中设置一个属性。 (The position is available from the event parameter.) (position 可从事件参数中获得。)sender()
to get the button, and read the property using property()
.在处理事件的槽中,使用sender()
获取按钮,并使用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.如果您不需要将 object 视为基础 class ( QPushButton*
),您可以创建一个包含鼠标事件的新信号并将其附加到您的插槽。 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.您可以使用 QCursor::pos() 获取当前鼠标 position,它在全局屏幕坐标中返回 cursor(热点)的 position。
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;基于@Liz 的简单机制,这就是我所做的; this is in a slot method that is called on pressed() but generalizes to other situations.这是在pressed() 上调用的槽方法中,但可以推广到其他情况。 Note that using pushButton->geometry() gives you coordinates that are already in global space so you don't need to mapFromGlobal.请注意,使用 pushButton->geometry() 会为您提供已经在全局空间中的坐标,因此您不需要 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.