user1647753
user1647753

Reputation:

I do not understand why this code would not open a file

I can not figure out why this code would not open a file please help. I have tried many different things but nothing works. I do not believe it even opens the file?

this is the 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();
}

this is my header.

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

this is the main 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()));

}

Upvotes: 0

Views: 145

Answers (1)

kenrogers
kenrogers

Reputation: 1350

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

Upvotes: 3

Related Questions