0

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

这是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

这是主window.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()));

}

4

1 回答 1

3

It doesn't open the file. You must open the file yourself, then create your QTextStream and pass it the opened file. Like this:

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

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

Your textstream needn't be a class member since you're only using it in the constructor. You can read all about using QFile and QTextStream here. http://qt-project.org/doc/qt-4.8/qfile.html

于 2013-03-08T19:53:29.307 回答