【问题标题】:I do not understand why this code would not open a file我不明白为什么这段代码不会打开文件
【发布时间】:2013-03-08 19:43:45
【问题描述】:

我不明白为什么这段代码不能打开文件,请帮忙。我尝试了很多不同的东西,但没有任何效果。我不相信它甚至打开文件?

这是main.cpp

#include "communicate.h"

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  Communicate window;

  window.setWindowTitle("Communicate");
  window.show();
  return app.exec();
}

这是我的标题。

using namespace std;
class Communicate : public QWidget
{
   Q_OBJECT

  public:
   Communicate(QWidget *parent = 0);


  //private slots:
  //void onenter();
  //void OnMinus();

  private:
    QFile namefile;
    QTextStream file;
    QString name;
    QLabel *label;
    QTextEdit *left;
    QTextEdit *right;
    QLineEdit *user;



};

#endif

这是主窗口.cpp

#include "communicate.h"
Communicate::Communicate(QWidget *parent)
    : QWidget(parent),namefile("pname.txt"),file(&namefile)
{

  QPushButton *enter = new QPushButton("enter", this);
  enter->setGeometry(205, 205, 90, 35);

  //QPushButton *minus = new QPushButton("-", this);
  //minus->setGeometry(50, 100, 75, 30);

  label = new QLabel("money: 500", this);
  label->setGeometry(105, 0, 90, 30);

  left = new QTextEdit(this);
  left ->setGeometry(0,0,100,200);

  right = new QTextEdit(this);
  right ->setGeometry(200,0,100,200);   

  user = new QLineEdit(this);
  user ->move(0,205);
  user ->resize(200,35);

  name=file.readLine();
  right->setText(name);
  label->setText(name);
  namefile.close();
  //connect(enter, SIGNAL(clicked()), this, SLOT(onenter()));
  //connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));

}

【问题讨论】:

  • 它应该如何知道它应该打开一个文件?我在代码末尾看到了对 close() 的调用,但没有看到对 open() 的单个调用。
  • 你说的很对,尽管知道是否打开文件的重要性不如如何打开文件文件。也就是说,它是在阅读吗?写作?截断?追加?文字?

标签: c++ file qt user-interface qfile


【解决方案1】:

它不会打开文件。您必须自己打开文件,然后创建您的QTextStream 并将打开的文件传递给它。像这样:

if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
     return;

 QTextStream in(&file);
 name = file.readLine();

您的文本流不必是类成员,因为您只在构造函数中使用它。您可以在此处阅读有关使用 QFile 和 QTextStream 的所有信息。 http://qt-project.org/doc/qt-4.8/qfile.html

【讨论】:

  • 好的,谢谢,但我认为我确实需要它作为班级成员,因为我将在其他功能中使用它。
  • 我能理解。但是,我建议你给这个类太多的责任。除非这只是一个尝试新事物或测试或其他什么的一次性项目,否则我会将文件打开和读取职责移到其他地方。考虑模型/视图/控制器模式,或其他分离职责的方式。
猜你喜欢
  • 2012-11-17
  • 2023-04-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 2012-09-01
  • 2010-12-14
相关资源
最近更新 更多