QWidget::move的偏移问题

本文探讨了Qt中move方法与setGeometry方法在设置窗口位置时的不同表现。move方法会考虑边框导致实际位置与预期有偏差,而setGeometry则直接设置窗口的几何尺寸,排除边框影响。通过示例代码和打印输出,展示了两种方法的使用效果,并解释了官方文档中的相关描述。理解这两个方法的差异对于精确控制Qt界面组件的位置至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

move设置位置但是不能到正确设置,但是用setGeometry是可以的

move设置位置是(0 , 0),但是实际位置为(10,42)

void fixSizeWidget::on_pushButton_clicked()
{
    QRect rect = QRect(0 , 0 , 1028 , 720);
    qDebug() << Q_FUNC_INFO << __LINE__ << "this->geometry() : " << this->geometry();
    qDebug() << Q_FUNC_INFO << __LINE__ << "rect.topLeft()" << rect.topLeft();
    this->move(rect.topLeft());
    qDebug() << Q_FUNC_INFO << __LINE__ << "this->geometry() : " << this->geometry();
    qDebug() << Q_FUNC_INFO << __LINE__ << "rect.topLeft()" << rect.topLeft();
    this->setFixedSize( 1028 , 720);
    qDebug() << Q_FUNC_INFO << __LINE__ << "this->geometry() : " << this->geometry();
    qDebug() << Q_FUNC_INFO << __LINE__ << "rect.topLeft()" << rect.topLeft();

    this->setGeometry(rect);
    qDebug() << Q_FUNC_INFO << __LINE__ << "this->geometry() : " << this->geometry();
}

 打印的信息

void fixSizeWidget::on_pushButton_clicked() 20 this->geometry() : QRect(760,362 400x300)

void fixSizeWidget::on_pushButton_clicked() 21 rect.topLeft() QPoint(0,0)

void fixSizeWidget::on_pushButton_clicked() 23 this->geometry() : QRect(10,42 400x300)

void fixSizeWidget::on_pushButton_clicked() 24 rect.topLeft() QPoint(0,0)

void fixSizeWidget::on_pushButton_clicked() 26 this->geometry() : QRect(10,42 1028x720)

void fixSizeWidget::on_pushButton_clicked() 27 rect.topLeft() QPoint(0,0)

void fixSizeWidget::on_pushButton_clicked() 30 this->geometry() : QRect(0,0 1028x720)

 找到原因了,因为使用move的时候会包括边框的偏移,move的官方文档

If the widget is a window, the position is that of the widget on the desktop, including its frame.

而setGeometry不包括边框,setGeometry的官方文档 

This property holds the geometry of the widget relative to its parent and excluding the window frame

这里所说的边框是frameGeometry和Geometry之间,如下图所示

文献参考:

Qt绘图:Window and Dialog Widgets 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值