我不明白为什么这段代码无法打开文件,请帮忙。我尝试了很多不同的东西,但没有任何效果。我不相信它甚至打开文件?
这是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()));
最佳答案
它不会打开文件。您必须自己打开文件,然后创建您的 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
关于c++ - 我不明白为什么这段代码无法打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302007/