user3404070
user3404070

Reputation:

QInputDialog center screen or center dialog

I have this code:

QString text = QInputDialog::getText(this, tr("Key:"), tr("Key:"), QLineEdit::Password, "", &ok);

I can't make this dialog appear center screen, I went through WindowFlags and I tried initializing QInputDialog as a variable, calling move and then calling getText, for sure it doesn't work either as window is not initialized yet to be moved. I don't want to create antoher thread/timer to move it after calling getText, it's not good idea.

Any ideas?

Upvotes: 1

Views: 1788

Answers (1)

Jablonski
Jablonski

Reputation: 18514

It will not work, because when you use QInputDialog as a variable, then you should not use static methods anymore. So you need something like next code which is equivalent to static method because call exec() (modal dialog by default). Works normal for me:

QString mText;
QInputDialog *inp = new QInputDialog(this);
inp->setLabelText(tr("Key:"));
inp->setWindowTitle(tr("Key:"));
inp->setTextEchoMode(QLineEdit::Password);
inp->adjustSize();
inp->move(QApplication::desktop()->screen()->rect().center() - inp->rect().center());
if(inp->exec() == QDialog::Accepted)
    mText = inp->textValue();
qDebug() << mText;

Also possible code to center dialog:

QSize screenSize = QApplication::desktop()->geometry().size();
int primaryScreenWidth = screenSize.width();
int primaryScreeHeight= screenSize.height();
int widgetWidth = inp->width();
int widgetHeight= inp->height();
inp->move(primaryScreenWidth/2 - widgetWidth/2, primaryScreeHeight/2 - widgetHeight/2);

Upvotes: 1

Related Questions