Вопрос

I have a class derived from QDialog. I have a single static instance that I show multiple times using exec. If a user manually resizes the dialog, I would like future calls to exec to launch it with the previous size.

I've seen some examples where QSettings was used, but it seems that there should be an easier solution since I still have the same QDialog instance in memory (also I don't necessarily want the settings to be persistent between runs of the application).

Whats the easiest way to have a dialog instance remember the size from the last call to exec?

Это было полезно?

Решение

Just use a static variable in your dialog class, here is a complete sample app (using 4.8.x):

#include <QApplication>
#include <QDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QDebug>

class MyDialog : public QDialog
{
    Q_OBJECT
public:
    MyDialog(QWidget *parent = 0) 
        : QDialog(parent) 
    {
        QHBoxLayout *layout = new QHBoxLayout(this);
        layout->addWidget(new QLabel("Test Label"));
    }

public Q_SLOTS:
    virtual int exec() { 
        resize(s_dialogSize);
        return QDialog::exec();
    }

protected:
    void closeEvent(QCloseEvent *event) { 
        Q_UNUSED(event)
        s_dialogSize = size();
    }

private:
    static QSize s_dialogSize;

};

QSize MyDialog::s_dialogSize;
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MyDialog dialog;
    qDebug() << dialog.exec();
    qDebug() << dialog.exec();
    qDebug() << dialog.exec();
    return app.exec();
}

#include "main.moc"

I've only implemented the closeEvent here, but if you want to save the size on accept/reject you need to save it to the variable in those methods as well (they are all virtual methods, and can be implemented in a similar fashion).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top