获取鼠标点击处的控件并获取其坐标(对控制控件和绘制控件都很实用)

int mouse_x = QCursor::pos().x();//鼠标点击处横坐标
int mouse_y = QCursor::pos().y();//鼠标点击处纵坐标

QWidget *action = QApplication::widgetAt(mouse_x, mouse_y);//获取鼠标点击处的控件
QPoint GlobalPoint(action->mapToGlobal(QPoint(0, 0)));//获取该控件在窗体中的坐标

int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
 

QT 获取控件widget的屏幕坐标

 :
方法一:
/// 获取窗口控件的屏幕位置,类似于ClientToScreen
QPoint GlobalPoint(widget->mapToGlobal(QPoint(0,0)));

方法二:
/// 获取窗口控件的屏幕位置
static QPoint getPos(QWidget* widget)
{
 if (NULL == widget)
 {
  return QPoint(-1,-1);
 }
 float px = 0;
 float py = 0;
 QWidget *parent = widget;
 QWidget *preParent= NULL;
 do
 {
  QPoint p = parent->pos();
  px += p.x();
  py += p.y();
  preParent = parent ;
  parentw = parent->parentWidget();
 
 } while (NULL != parent);
 QSize size = preParent->frameSize();
 QSize size2 = preParent->size();
 px = px + (size.width() - size2.width())/2;
 py = py + (size.height() - size2.height() - (size.width() - size2.width())/2);
 QPoint pr(px, py);
 return pr;
}

http://blog.csdn.net/mingxia_sui/article/details/7943169
posted @ 2016-06-02 17:42  findumars  Views(8072)  Comments(0Edit  收藏  举报