You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt6 Widget应用启动时如何定位到屏幕右上角?CMake相关问题求助

Qt6 Widget窗口启动时定位到屏幕右上角的解决方案

关于QDesktopWidget的问题

Qt6已经彻底移除了QDesktopWidget类,不存在所谓“安装CMake的QDesktopWidget库”的说法。Qt6推荐使用QScreen类来获取屏幕相关信息,你代码里已经引入了QScreen,用它就足够实现需求。

原代码的问题分析与修正

你当前的定位逻辑有误,导致窗口没出现在预期位置:

  • QWidget::move(sc.top(), sc.right())参数逻辑错误:move接收的是窗口左上角的x, y坐标,sc.top()是屏幕顶部的y值(通常为0),sc.right()是屏幕宽度,这样设置会把窗口左上角放到(0, 屏幕宽度)的位置,窗口直接跑到屏幕外了。
  • 正确逻辑应该是让窗口右上角对齐屏幕右上角:屏幕宽度减去窗口宽度就是窗口左上角的x坐标,y坐标保持为0(屏幕顶部)。
  • 另外代码里的Widget::show()应改为this->show(),析构函数末尾还缺了闭合的}。

修正后的代码如下:

#include "widget.h"
#include "./ui_widget.h"
#include <QScreen>
#include <QRect>
#include <QSize>
#include <QApplication>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::WindowType::FramelessWindowHint);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setStyleSheet(".QFrame{background-color: red; border: 1px solid black; border-radius: 10px;}");

    // 获取主屏幕几何信息
    QRect screenRect = QGuiApplication::primaryScreen()->geometry();
    // 确保窗口尺寸已计算完成(如果UI里的尺寸是动态的)
    this->adjustSize();
    // 计算窗口左上角坐标:屏幕宽度 - 窗口宽度,y轴贴屏幕顶部
    int targetX = screenRect.width() - this->width();
    int targetY = 0;
    this->move(targetX, targetY);
    
    this->show();
}

Widget::~Widget()
{
    delete ui;
}

内容的提问来源于stack exchange,提问作者Ömer Gültekin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:05:38