I would like to share an object (a QDir) between several pages of a QWizard, so that if one page changes the value of this directory, this carries through to all other pages.nSince this object is not optional, I would like to share it by passing a reference rather than a pointer so I do not need to worry about a possible null pointer (is this correct? I've read opinions both ways). Here is a minimal test case:
test.hpp:
#include <QApplication>
#include <QWizard>
#include <QDir>
#include <QVBoxLayout>
#include <QWizardPage>
#include <QLineEdit>
class TestWizard : public QWizard {
Q_OBJECT
public:
TestWizard(QWidget* parent = 0);
QDir directory;
};
class TestPage : public QWizardPage {
Q_OBJECT
public:
TestPage(QDir& _directory, int _id, QWidget* parent = 0);
void initializePage();
public slots:
void setDirectory(QString new_dir);
private:
QVBoxLayout* layout;
QDir directory;
QLineEdit* dir_edit;
int id;
};
test.cpp:
#include "test.hpp"
#include <iostream>
TestWizard::TestWizard(QWidget* parent) : QWizard(parent){
directory = QDir();
addPage(new TestPage(directory, 0));
addPage(new TestPage(directory, 1));
addPage(new TestPage(directory, 2));
}
TestPage::TestPage(QDir& _directory, int _id, QWidget* parent)
: QWizardPage(parent){
directory = _directory;
id = _id;
layout = new QVBoxLayout;
dir_edit = new QLineEdit;
layout->addWidget(dir_edit);
this->setLayout(layout);
connect(dir_edit, SIGNAL(textChanged(QString)),
this, SLOT(setDirectory(QString)));
}
void TestPage::initializePage(){
std::cout << id << ": " << directory.absolutePath().toUtf8().constData()
<< std::endl;
}
void TestPage::setDirectory(QString new_dir){
directory.setPath(new_dir);
}
int main(int argc, char* argv[]){
QApplication app(argc, argv);
TestWizard wizard;
wizard.show();
return app.exec();
}
Clicking through this and editing the text gives the result that changing one text only affects the directory
variable on one page. I know how to do this with a pointer, but I would like to understand why this does not work.
It looks like I have a basic misconception somewhere about what is behind this and I'd like to clear it up before I do something stupid :)
I think I have been a bit of an idiot, but just to confirm:
test.cpp:
TestPage::TestPage(QDir& _directory, int _id, QWidget* parent)
: QWizardPage(parent){
directory = _directory; // This is where I'm going wrong
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.