Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Center QDialog to desktop
QtWS25 Last Chance

Center QDialog to desktop

Scheduled Pinned Locked Moved Solved General and Desktop
9 Posts 5 Posters 1.1k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Stefanoxjx
    wrote on last edited by
    #1

    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.

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      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 ?

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      2
      • S Offline
        S Offline
        Stefanoxjx
        wrote on last edited by Stefanoxjx
        #3

        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.

        JonBJ 1 Reply Last reply
        0
        • S Stefanoxjx

          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.

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by JonB
          #4

          @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.

          S 1 Reply Last reply
          5
          • JonBJ JonB

            @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.

            S Offline
            S Offline
            Stefanoxjx
            wrote on last edited by
            #5

            @JonB Yeah, it works fine :)
            Thanks.

            Thank YouT 1 Reply Last reply
            0
            • S Stefanoxjx

              @JonB Yeah, it works fine :)
              Thanks.

              Thank YouT Offline
              Thank YouT Offline
              Thank You
              wrote on last edited by
              #6

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

              Thank You

              Let's make QT free or It will go forever

              TRUE AND FALSE <3

              S 1 Reply Last reply
              1
              • Christian EhrlicherC Offline
                Christian EhrlicherC Offline
                Christian Ehrlicher
                Lifetime Qt Champion
                wrote on last edited by
                #7
                This post is deleted!
                1 Reply Last reply
                0
                • Thank YouT Thank You

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

                  Thank You

                  S Offline
                  S Offline
                  Stefanoxjx
                  wrote on last edited by
                  #8

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

                  Thank YouT 1 Reply Last reply
                  0
                  • S Stefanoxjx

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

                    Thank YouT Offline
                    Thank YouT Offline
                    Thank You
                    wrote on last edited by
                    #9

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

                    Let's make QT free or It will go forever

                    TRUE AND FALSE <3

                    1 Reply Last reply
                    0

                    • Login

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • Users
                    • Groups
                    • Search
                    • Get Qt Extensions
                    • Unsolved