[英]Sharing object by reference (in Qt)
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). 我想在一个QWizard的多个页面之间共享一个对象(一个QDir),以便如果一个页面更改了该目录的值,则该对象会传递到所有其他页面。n由于该对象不是可选的,因此我想共享它通过传递引用而不是指针来实现,因此我不必担心可能存在的空指针(这是正确的吗?我已经阅读了两种方式的观点)。 Here is a minimal test case:
这是一个最小的测试用例:
test.hpp: 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: 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. 单击此按钮并编辑文本会导致更改一个文本仅影响一页上的
directory
变量的结果。 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: test.cpp:
TestPage::TestPage(QDir& _directory, int _id, QWidget* parent)
: QWizardPage(parent){
directory = _directory; // This is where I'm going wrong
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.