Qt: C++: Restoring geometry of a pop-up dialog-box

旧城冷巷雨未停 提交于 2019-12-24 17:14:05

问题


I am trying to save the geometry of a pop-up dialog-box and then restore it back whenever I call the pop-up dialog box (while the application is still running).

But I couldn't figure it out.

The code runs without error. But the window of the pop-up keeps changing it position vertically everytime it is open. Unless I close the whole application and then re-opened it again, the pop-up never goes to its original position in the center of the screen.

I am trying to use QcloseEvent, QSettings and restoreGeometry. But something is not right, please help.

Here is MainWindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_addmembersdialog.h"
#include "addmembersdialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mpAddMembersDialog = new AddMembersDialog;
    connect(ui->testBtn,SIGNAL(clicked()),this,SLOT(openPopUpForm()));
}

void MainWindow::openPopUpForm(){
    mpAddMembersDialog->readSettings();
    mpAddMembersDialog->exec();
}

Here is AddMembersDialog.cpp:

#include "addmembersdialog.h"
#include "ui_addmembersdialog.h"
#include <QMessageBox>

AddMembersDialog::AddMembersDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddMembersDialog)
{
    ui->setupUi(this);
    connect(ui->closeFormBtn,SIGNAL(clicked()),this,SLOT(Exit()));
}
void AddMembersDialog::Exit()
{
    close();
}

void AddMembersDialog::closeEvent(QCloseEvent *event){
    QSettings settings("DevSuda", "Muwassa");
    settings.setValue("geometery", saveGeometry());
    QDialog::closeEvent(event);
}

void AddMembersDialog::readSettings(){
    QSettings settings("DevSuda", "Muwassa");
    restoreGeometry(settings.value("QDialog/geometry").toByteArray());
}

回答1:


Please compare the key used for the following two lines:

settings.setValue("geometery", saveGeometry());

and

restoreGeometry(settings.value("QDialog/geometry").toByteArray());

"geometry" vs "QDialog/geometry". Should be the same!

also I would predefine your keys/organization/application name in the cpp file such as:

...
static const char * ksOrganization{"DevSuda"};
static const char * ksApp         {"Muwassa"};
static const char * ksKey         {"geometery"};
...
QSettings settings(ksOrganization, ksApp);
settings.setValue(ksKey, saveGeometry());

This would prevent you from typing the key wrong in one place...



来源:https://stackoverflow.com/questions/36860487/qt-c-restoring-geometry-of-a-pop-up-dialog-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!