user3360601
user3360601

Reputation: 347

How to set programmatically QWidget in the center of the window in Qt?

I have such code on Qt.

wdgCenter = new QWidget(wdgMain);
wdgCenter->move(wdgCenter->parentWidget()->geometry().center());
wdgCenter->resize(QSize(170, 115));

welcomeLbl = new QLabel("Welcome to the Notes. Log in first.", wdgCenter);
welcomeLbl->setGeometry(QRect(QPoint(0, 0), QSize(175, 20)));

loginLbl = new QLabel("Login", wdgCenter);
loginLbl->setGeometry(QRect(QPoint(0, 30), QSize(50, 20)));

pswdLbl = new QLabel("Password", wdgCenter);
pswdLbl->setGeometry(QRect(QPoint(0, 60), QSize(50, 20)));

loginLine = new QLineEdit (wdgCenter);
loginLine->setGeometry(QRect(QPoint(60, 30), QSize(110, 20)));

passwordLine = new QLineEdit (wdgCenter);
passwordLine->setGeometry(QRect(QPoint(60, 60), QSize(110, 20)));

logInBtn = new QPushButton ("Log In", wdgCenter);
logInBtn->setGeometry(QRect(QPoint(0, 90), QSize(50, 25)));

createBtn = new QPushButton ("Create", wdgCenter);
createBtn->setGeometry(QRect(QPoint(60, 90), QSize(50, 25)));

The result you can see below on the first picture.

default picture

I want to move my wdgCenter to the center of the window. I tried QGridLayout like this below.

QGridLayout* gLayout = new QGridLayout(wdgMain);

gLayout->addWidget( welcomeLbl );
gLayout->setAlignment(welcomeLbl,Qt::AlignHCenter);
gLayout->addWidget( loginLbl, 1, 0  );
gLayout->setAlignment(loginLbl,Qt::AlignHCenter);
gLayout->addWidget( pswdLbl, 2, 0 );
gLayout->setAlignment(pswdLbl,Qt::AlignHCenter);
gLayout->addWidget( loginLine, 1, 1 );
gLayout->setAlignment(loginLine,Qt::AlignHCenter);
gLayout->addWidget( passwordLine, 2, 1 );
gLayout->setAlignment(passwordLine,Qt::AlignHCenter);
gLayout->addWidget( logInBtn, 3, 0 );
gLayout->setAlignment(logInBtn,Qt::AlignHCenter);
gLayout->addWidget( createBtn, 3, 1 );
gLayout->setAlignment(createBtn,Qt::AlignHCenter);

And the result you can see on the next picture below.

enter image description here

I also tried QHBoxLayout and QHBoxLayout but they just draw me my objects in on row or in one column.

In Qt Designer I did this with vertical and horizontal spacers like this:

enter image description here

But I need to do this programmatically.

How to set my wdgCenter to The center?

Upvotes: 0

Views: 893

Answers (1)

frogatto
frogatto

Reputation: 29285

A simple way would be designing the UI using Qt Designer and let it generate the source code. Auto-generated source code for the UI is in a .h file called ui_<your class name>.h, for example: ui_mainwindow.h. This file is included automatically in <your class name>.cpp file, so you can find it there.

The Qt Designer overview:

enter image description here

Result:

enter image description here

Upvotes: 1

Related Questions