Search code examples
c++qtqprogressdialog

How to move cancel button in QProgressDialog to the center?


I want to move the Cancel button of QProgressDialog to the center; by default its on the left.

Below is a simple example, but I don't know how to change the button position.

_progress = new QProgressDialog();
_progress->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
_progress->setWindowTitle(tr("Stimulated Movement"));
_progress->setLabelText(tr("Please wait for a moment while the motor is moving!"));
_progress->setAttribute(Qt::WA_DeleteOnClose);
_progress->setModal(true);
//make it Keep rolling
_progress->setRange(0, 0);
_progress->setCancelButton(new QPushButton(tr("Terminate")));

Solution

  • Remy Lebeau said:

    You have access to the QPushButton for the cancel, what's stopping you from simply moving it where you want when the dialog is shown?

    Here's how you can implement that:

    QProgressDialog *progress = new QProgressDialog();
    progress->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    progress->setWindowTitle("Stimulated Movement");
    progress->setLabelText("Please wait for a moment while the motor is moving!");
    progress->setAttribute(Qt::WA_DeleteOnClose);
    progress->setModal(true);
    progress->setRange(0, 0);
    QPushButton *b = new QPushButton("Terminate");
    progress->setCancelButton(b);
    
    progress->show();
    //move it to the center of progress after you show it
    //y coordinate stays the same, and you have to calculate x relatively to the button and dialog width 
    b->move((progress->width()-b->width())/2,b->geometry().y());
    

    However there is a problem with this method, the button will not stay in the center if the dialog is resized.

    Fixing that, needs resizeEvent reimplementation, but if you don't need resizing, you might just want to set a fixed size for the dialog to prevent it.

    For example:

    progress->setFixedSize(310,100);