【问题标题】:How to Align mainwindow to the right of the screen in Qt 5.1.0如何在 Qt 5.1.0 中将主窗口对齐到屏幕右侧
【发布时间】:2025-12-10 08:30:02
【问题描述】:

此代码正在运行:

QRect r = QApplication::desktop()->availableGeometry();
QRect main_rect = this->geometry();
main_rect.moveTopRight(r.topRight());
this->move(main_rect.topLeft()); 

此代码正在处理屏幕的位置。但我想对齐到屏幕的右侧..

你有什么想法吗?

谢谢你..

【问题讨论】:

    标签: c++ qt alignment screen


    【解决方案1】:

    我认为你应该在你的主布局中使用 setAlignment 像这样

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->setAlignment(Qt::AlignRight);
    

    【讨论】:

    • 转到Design并单击MainWindow上的某处,然后在属性窗口中找到layoutDirection并将其更改为RightToLeft
    【解决方案2】:

    我有一个解决方案,但遗憾的是它并不那么容易......

    首先,您必须在短暂的延迟后进行移动,您可以阅读更多关于它的信息here (Check the accepted answere)

    要移动窗口,您必须执行以下操作:

    void MainWindow::timerEvent(QTimerEvent *event)
    {
    
        if(event->timerId() == this->TimerID)
        {
            event->accept();
            this->killTimer(this->TimerID);
            //Used to kill the timer that was created in the constructor, needs the ID to do this
    
            QRect desktopGeom = QApplication::desktop()->availableGeometry(); //Screen size
            QRect windowFrame = this->frameGeometry(); //Window with frame
            QRect windowSize = this->geometry(); //Window without frame
    
            int smallFrameFactor = (windowFrame.width() - windowSize.width()) / 2; //Because the left, right and bottom border have the same size
            int wideFrameFactor = windowFrame.height() - (windowSize.height() + smallFrameFactor); //The big, upper border
    
            int x_pos = desktopGeom.x() + desktopGeom.width() - windowSize.width() - smallFrameFactor;
            int y_pos = desktopGeom.y() + wideFrameFactor;
    
            this->setGeometry(x_pos, y_pos, windowSize.width(), windowSize.height());
        }
        else
            event->ignore();
    }
    

    我添加了一张图片,以可视化我在上面所做的事情。希望能帮到你。

    编辑:刚刚看到这个问题已经有一年多了......也许它对某人仍然有帮助......

    【讨论】: