I want to read a file and to put it in a Qstring but the file doesn't be read I have searched for many sample in google but it doesn't work... I want read the file...

using namespace std;

 int main(int argc, char *argv[])

 {

    QApplication app(argc, argv);


    QFile in1("file.txt");

    QTextStream in(&in1);

    if (in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("read");
        label->show();
    }

    if (!in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("!read");
        label->show();
    }
    QString s1;

    in >> s1;

    QLabel *label = new QLabel(s1);

    label->show();

    return app.exec();

 }

show me: !read

I included everything that you can think and file.txt is in true place ??!! :-(

有帮助吗?

解决方案

This code works for me below.

file.txt

Hello World!

main.cpp

#include <QLabel>
#include <QApplication>

#include <QFile>
#include <QTextStream>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QFile in1("file.txt");
    QTextStream in(&in1);

    if (in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("read");
        label->show();
    }

    if (!in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("!read");
        label->show();
    }

    QString s1;
    in >> s1;

    QLabel *label = new QLabel(s1);
    label->show();
    return app.exec();
}

Build

g++ -Wall -fPIC -lQt5Core -lQt5Widgets -I/usr/include/qt -I/usr/include/qt/QtCore -I/usr/include/qt/QtWidgets main.cpp && ./a.out

or the main.pro qmake project file:

TEMPLATE = app
TARGET = main
greaterThan(QT_MAJOR_VERSION, 4):QT += widgets
SOURCES += main.cpp

It will show all the three labels for me, but I am not sure if that is what you wanted. The error handling is missing in your code, too.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top