Qt中,如何找准控件坐标

时间:2025-10-28 09:55:37

1、实现:

需要对qt的坐标有了解:

QPoint QWidget::mapToParent(const QPoint & pos) const

QPoint QWidget::mapTo(const QWidget * parent, const QPoint & pos) const

QPoint QWidget::mapToGlobal(const QPoint & pos) const

A、这三个函数都应该是控件的父窗口对象才能调用的,不应该是控件本身调用。

B、控件的父窗口应该是QFrame、QWidget,但不能是QLayout之类。

2、代码如下:

void TestWidget::on_pushButton123_clicked()  

{      

     QPoint p = ui.pushButton123->pos();//获得pushButton123在父窗口(frame_2)中的相对坐标,值为[10,10]      

     QPoint pos1 = ui.frame_2->mapTo(this, ui.pushButton123->pos());//将父窗口(frame_2)中的按钮坐标,转换成当前窗口(TestWidget)的坐标,值为[40,120]      

     QPoint pos1_1 = ui.pushButton123->mapTo(this, ui.pushButton123->pos());//错误方法,值为[50,130]     

      QPoint pos2 = ui.frame_2->mapToParent(ui.pushButton123->pos());//错误方法,值为[40,120]      

     QPoint pos2_1 = ui.pushButton123->mapToParent(ui.pushButton123->pos());//错误方法,值为[20,20]      

     QPoint pos3 = ui.frame_2->mapToGlobal(ui.pushButton123->pos());//错误方法,值为[300,333]     

      QPoint pos3_1 = ui.pushButton123->mapToGlobal(ui.pushButton123->pos());//错误方法,值为[310,343]  

}  

3、最终实验结果:

Qt中,如何找准控件坐标

Qt中,如何找准控件坐标

© 2025 光影知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com