Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Center QDialog to desktop



  • Hi, I can't center window in desktop.
    I read some documentation and I decided to use this solution:

    this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, this->size(), qApp->desktop()->availableGeometry()));
    

    (yes I saw, this is deprecated :( )
    I've placed this code at finish of constructor, before this.exec().
    But seems to work not very fine.

    I've the QDialog centered in x axis, but in y it goes in lower part of desktop.

    The problem is that the window size is not real.
    I've width 640 and height 30.
    The width is ok because I've set setMinimumWidth, but for height I haven't set nothing and infact is very small (30).
    How I can know real size of QDialog before to run exec method?

    Thanks.


  • Lifetime Qt Champion

    Hi,

    That won't work because a widget only gets its "physical size" once shown.

    Which version of Qt are you using ?
    Can you share your code ?



  • Hi SGaist, I use version 5.15.1.
    This is the interested part of code:

    GenericDialog.h

    #ifndef GENERICDIALOG_H
    #define GENERICDIALOG_H
    
    #include <QDialog>
    #include <QToolBar>
    #include <QAction>
    #include <QTableWidget>
    #include <QTableWidgetItem>
    #include <QWidget>
    #include <QCloseEvent>
    #include <QLayout>
    #include "logs.h"
    #include "mainwindow.h"
    
    class GenericDialog : public QMainWindow, public Logs
    {
        Q_OBJECT
    
    public:
        typedef enum
        {
            AddFindMode,
            EditMode,
            DeleteMode
        } SwitchMode_t;
    
        typedef enum
        {
            opNone,
            opAddNew,
            opModify,
            opDelete,
        } Operation_t;
    
        //*** Toolbar
        QAction             *tbApply;
        QAction             *tbBack;
        QAction             *tbAdd;
        QAction             *tbDelete;
        QAction             *tbEdit;
        QAction             *tbFind;
        QAction             *tbExit;
    
        //*** Layouts
        QVBoxLayout *MainLayout;
    
        //*** Vars
        static uint32_t                RecId; // = 0;
        static Operation_t             OperationType;
    
    
        MainWindow              *mw;
    
        //*** Prototype
                         GenericDialog      (QWidget *parent = nullptr);
        void             ExecuteDialog      (void) {this->show();}
        void             SetWorkingTable    (QString table) {WorkTable = table;}
        void             ToolBarSwitchTo    (SwitchMode_t);
        void             SetWidgetWidth     (QLineEdit *, uint16_t);
        QTableWidgetItem *AddItem           (QString, Qt::Alignment);
        QFrame           *HLine             (void);
        uint16_t         CalcColumnWidth    (QTableWidget *, uint16_t);
    
        uint32_t         GetRecId           (void) {return RecId;}
    
        //*** Virtual func
        virtual void    ResetEditWindow     (void);
    
    
    private:
        QString                 WorkTable;
    
        void    closeEvent         (QCloseEvent *);
    
    public slots:
                void        sltCloseDialog      (void) {this->close();}
        virtual void        sltAdd              (void);
        virtual void        sltDelete           (void);
        virtual void        sltEdit             (void);
        virtual bool        sltBack             (void);
        virtual void        sltFind             (void) = 0;
        virtual void        sltSelected         (void) = 0;
        virtual void        sltDataConfirm      (void) = 0;
    };
    
    #endif // GENERICDIALOG_H
    

    GenericDialog.cpp (Only interested parts)

    uint32_t GenericDialog::RecId = 0;
    GenericDialog::Operation_t GenericDialog::OperationType = GenericDialog::opNone;
    
    GenericDialog::GenericDialog(QWidget *parent) : QMainWindow(parent)
    {
        mw = dynamic_cast<MainWindow*>(parent);
    
        setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
    
         //Toolbar
        QToolBar *ToolBar = new QToolBar();
    
        tbApply = ToolBar->addAction("Conferma");
        tbApply->setIcon(QIcon(":/Icons/Apply.ico"));
    
        tbBack = ToolBar->addAction("Annulla");
        tbBack->setIcon(QIcon(":/Icons/Back.ico"));
    
        tbAdd = ToolBar->addAction("Aggiungi nuovo");
        tbAdd->setIcon(QIcon(":/Icons/Add.ico"));
    
        tbDelete = ToolBar->addAction("Elimina");
        tbDelete->setIcon(QIcon(":/Icons/Delete.ico"));
    
        tbEdit = ToolBar->addAction("Modifica");
        tbEdit->setIcon(QIcon(":/Icons/Edit.ico"));
    
        tbFind = ToolBar->addAction("Cerca");
        tbFind->setIcon(QIcon(":/Icons/Find.ico"));
        tbFind->setShortcutVisibleInContextMenu(true);
        tbFind->setToolTip("Cerca (CTRL+L)");
        tbFind->setShortcut(Qt::CTRL+Qt::Key_L);
    
        tbExit = ToolBar->addAction("Esci");
        tbExit->setIcon(QIcon(":/Icons/Exit.ico"));
    
        ToolBarSwitchTo(AddFindMode);
    
        //Imposto Widget e Layout principale
        QWidget *Window = new QWidget;
        MainLayout = new QVBoxLayout();
        Window->setLayout(MainLayout);
        setCentralWidget(Window);
    
        layout()->setMenuBar(ToolBar);
    
        //Segnali Toolbar
        connect(tbApply, SIGNAL(triggered()), this, SLOT(sltDataConfirm()));
        connect(tbBack, SIGNAL(triggered()), this, SLOT(sltBack()));
        connect(tbAdd, SIGNAL(triggered()), this, SLOT(sltAdd()));
        connect(tbDelete, SIGNAL(triggered()), this, SLOT(sltDelete()));
        connect(tbEdit, SIGNAL(triggered()), this, SLOT(sltEdit()));
        connect(tbFind, SIGNAL(triggered()), this, SLOT(sltFind()));
        connect(tbExit, SIGNAL(triggered()), this, SLOT(sltCloseDialog()));
    }
    

    Employees.h

    class Employees : public GenericDialog
    {
        Q_OBJECT
    
    public:
        Employees(QWidget *parent = nullptr);
        ~Employees() {IsOpen = false;}
    
    private:
    ...
    
    private slots:
    ...
    };
    

    Employees.cpp (constructor)
    Employees::Employees(QWidget *parent) : GenericDialog(parent)
    {
    IsOpen = true;

    setWindowTitle("Dipendenti");
    setWindowIcon(QIcon(":/Icons/Employees.ico"));
    
    SetWorkingTable("Dipendenti");
    
    QVBoxLayout *vl1 = new QVBoxLayout;
    MainLayout->addLayout(vl1);
    
    //TABs
    tabMain = new QTabWidget;
    tabMain->addTab(CreateGenericView(), "Generale");
    tabMain->addTab(CreateMansioniView(), "Dati"); 
    tabMain->addTab(CreateFormazioneView(), "Contatti");
    ...
    
    connect(tabMain, SIGNAL(currentChanged(int)), this, SLOT(sltTabChanged(int)));
    
    this->setMinimumWidth(tabMain->width());
    
    vl1->addWidget(tabMain);
    
    this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, this->size(), qApp->desktop()->availableGeometry()));
    
    ExecuteDialog();
    

    }

    Hope this is enough.
    Thanks.



  • @Stefanoxjx said in Center QDialog to desktop:

    this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, this->size(), qApp->desktop()->availableGeometry()));

    Just before this line, try putting in qDebug() << this->size(). I think @SGaist is telling you it will not be correct, because you are calling it in the constructor, but a widget does not get a meaningful size until it is first shown.

    Try moving it into an override of https://doc.qt.io/qt-5/qwidget.html#showEvent, like:

    protected:
    virtual void showEvent(QShowEvent *event) override
    {
        GenericDialog::showEvent(event);
        this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, this->size(), qApp->desktop()->availableGeometry()));
    }
    

    Later you might put in a flag to detect and only set the geometry the first time showEvent() is called, because it is also called e.g. if you minimize and then maximize a window.



  • @JonB Yeah, it works fine :)
    Thanks.



  • @Stefanoxjx If @JonB answer helped you then you can change the question status from unsolved to solved

    Thank You


  • Qt Champions 2019

    This post is deleted!


  • @Thank-You Ops!!! Excuseme, I forgot it :(



  • @Stefanoxjx Great๐Ÿ˜Š๐Ÿ˜ŠโœŒ


Log in to reply