【发布时间】:2013-05-16 19:07:45
【问题描述】:
我目前正在从事一个基础学校项目,但我不知道如何解决我目前遇到的问题。请记住,我是 C++ 和 Qt 的初学者,所以错误可能是微不足道的(我希望这样!)
我正在尝试使用我最近开发的一个类:ArticleEditor。此类继承自 QWidget,基本上是一个小窗口,您可以在其中编辑文章(标题和文本)并保存修改。目前,通过创建 ArticleEditor 的实例并将其显示在 main.cpp 文件中,我已经设法以基本方式使用该类,但现在我正在尝试做一些更棘手的事情。
关键是在选择文件后打开一个 ArticleEditor 小部件/窗口。我已经毫无问题地完成了文件选择部分,但是当我选择了我的文件时,ArticleEditor 小部件打开并且......完全是空的。我在其构造函数中的 setSize 中设置的大小被考虑在内,但我设置并添加到布局中的小部件(也在构造函数中)不存在,也不可见。
这是我的代码,应该可以帮助您了解情况:
ArticleEditor.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...
【问题讨论】:
-
你最好去掉 move() 调用,它们不会有任何区别——无论如何,QVBoxLayout 都会重新定位你添加到其中的小部件。
-
谢谢,我忘记了,现在去掉那些多余的行。
-
制作了测试应用,对我有用
-
该类本身工作正常,请详细说明您如何称呼它,更具体地说,关于 articleWidget。您是否将您的 ArticleEditor aE 添加到 arcticleWidget 的布局中?