我目前正在做一个基础学校项目,但我不知道如何解决我目前遇到的问题。请记住,我是 C++ 和 Qt 的初学者,因此错误可能微不足道(我希望如此!)
我正在尝试使用我最近开发的一个类:ArticleEditor。这个类继承自 QWidget,基本上是一个小窗口,您可以在其中编辑文章(标题和文本)并保存修改。目前,我已经设法以基本方式使用此类,方法是创建 ArticleEditor 的实例并将其显示在 main.cpp 文件中,但现在我正在尝试做一些更棘手的事情。
重点是在选择文件后打开一个 ArticleEditor 小部件/窗口。我已经毫无问题地实现了文件选择部分,但是当我选择了我的文件时,ArticleEditor 小部件打开并且......完全是空的。我在其构造函数内的 setSize 中设置的大小被考虑在内,但我正在设置和添加到布局中的小部件(也在构造函数中)不存在,也不可见。
这是我的代码,应该可以帮助您了解情况:
文章编辑器.cpp: enableSave() 用于在您编辑两个文本字段之一时启用保存按钮,saveArticle() 是另一种方法,此处不重要。
ArticleEditor::ArticleEditor(Article* article, QWidget *parent) :
QWidget(parent)
{
title = new QLineEdit();
title->setFixedWidth(180);
title->move(10,10);
text = new QTextEdit();
text->setFixedSize(180,110);
text->move(10,45);
save = new QPushButton();
save->setText("Save");
save->setFixedWidth(80);
save->move(10,170);
save->setEnabled(false);
title->setText(article->getTitle());
text->setText(article->getText());
QObject::connect(save, SIGNAL(clicked()), this, SLOT(saveArticle()));
QObject::connect(title, SIGNAL(textChanged(const QString)), this, SLOT(enableSave()));
QObject::connect(text, SIGNAL(textChanged()), this, SLOT(enableSave()));
layout = new QVBoxLayout;
layout->addWidget(title);
layout->addWidget(text);
layout->addWidget(save);
this->setFixedSize(200,200);
this->setLayout(layout);
}
ArticleEditor.h
class ArticleEditor : public QWidget
{
Q_OBJECT
public:
explicit ArticleEditor(Article* article, QWidget* parent);
private:
QLineEdit* title;
QTextEdit* text;
QPushButton* save;
QVBoxLayout* layout;
Article* ressource;
public slots:
void saveArticle();
void enableSave();
private slots:
};
选择一个文件后(我不打算提供详细信息,因为获取路径已经工作正常),我会做类似的事情:
ArticleEditor aE(&a, articleWidget); // calling the constructor with an article I've fetched using the path, and setting articleWidget (a private attribute) to be the parent
articleWidget->show(); // showing the result
在这里,articleWidget 是我的类的一个属性,创建为 articleEditor 实例的父小部件。
我也试过直接将布局设置到父小部件(parent->setLayout(layout) 而不是 this->setLayout(layout),但是每当我这样做时,小部件的内容都会显示,但我的信号/slots 连接不再工作了...
如果有人能向我解释我做错了什么,我将不胜感激。
编辑:我刚刚注意到,即使在将小部件添加到我的布局之后,当我尝试 layout->isEmpty() 时,我的返回值也是 true...
最佳答案
我认为在 ArticleEditor.cpp
中,您需要使您的布局成为小部件的子级
layout = new QVBoxLayout(this);
您的小部件也应该是 ArticleEditor 小部件的子项;即 title
、text
和 save
。
关于c++ - 布局已设置,但 QWidget 仍然看起来是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679776/