Issue with qmessagebox, can't change its position

梦想的初衷 提交于 2019-12-12 04:18:47

问题


I have this

int MainWindow::messageBox( QString button, QMessageBox::ButtonRole buttons, QString info, QMessageBox::Icon icon )
{
    QFont f;

    f.setPointSize(6);

    QMessageBox *message = new QMessageBox(this);
    message->setWindowModality(Qt::WindowModal);
    message->setFont(f);
    message->setText(info);
    message->addButton( button, buttons );
    message->setWindowTitle("MainWindow");
    message->setIcon(icon);
    message->move( this->width() / 2, this->height() / 2 );

    return message->exec();
}

But I can't make the qmessagebox go to the center of the screen, I also tried using setGeometry, but it doesn't work. Any ideas on this?


回答1:


I solved using show() before moving it. This is the code:

int MainWindow::messageBox( QString button, QMessageBox::ButtonRole buttons, QString info, QMessageBox::Icon icon )
{
    QFont f;
    QMessageBox *message = new QMessageBox(this);
    QDesktopWidget *win = new QDesktopWidget();

    f.setPointSize(6);

    message->setWindowModality(Qt::WindowModal);
    message->setFont(f);
    message->setText(info);
    message->addButton( button, buttons );
    message->setWindowTitle("MainWindow");
    message->setIcon(icon);
    message->show();
    message->move( win->width() / 2 - message->width() / 2, win->height() / 2 - message->height() / 2 );

    return message->exec();
}



回答2:


A QMessageBox is created with the window flag Qt::Dialog (and indirectly, Qt::Window). This means that it will be treated like a system window even though it has a parent assigned. When you call move() on it, it will be positioned in desktop coordinates.

When you move the message box in your code above, you are telling it to appear at desktop coordinates equal to half the width and height of your main application window size offset from origin (the top left corner of you desktop).

If your main application window has a size of 400x200, then your message box will appear at desktop coordinates 200,100 no matter where your main application window is located.

If you make your application window full screen and then display the message box, the message box should appear (roughly) at the center of your desktop display. I say roughly because you are specifying the position of the top left corner of the message box, not where the center of the message box will appear to be.

If you want the message box to always appear at the center of the screen, then you need to use the information provided by QDesktopWidget to determine what the correct screen coordinates should be.



来源:https://stackoverflow.com/questions/9234424/issue-with-qmessagebox-cant-change-its-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!