Important: Please read the Qt Code of Conduct -

Can't read from file.

  • This is a really stupid question, but for the life of me, I can't figure out how to read one line of text from a .txt file. Everytime, it says in the console "QIODevice::read: device not open". This is my code.

    void Widget::printLine(){
        QFile myFile(":/conversations.txt");
    | QIODevice::Text);
        QTextStream conversations(&myFile);
        QString line = conversations.readLine();

    I've tried putting in the whole address (C:/users...) but that doesn't work. I've also tried adding a resource file and adding a prefix, /, then adding the text file to it. And I've also tried putting it in the same directory as the project (where all the .cpp's and stuff are). I'm almost certain that the problem is because it can't open the file, because I've done different tests to make sure of that. Any ideas what is wrong? Thanks in advance.

  • Lifetime Qt Champion


    If you use the ":/XX" syntax then the file must be in a qresource file
    included in the project.

    Have you check what open returns ?
    if(! | QFile::Text))
    qDebug() << " Could not open the file for reading";

    a full path to the file "c:/user/xx/conversations.txt" should have worked.

    If you try the qresource way again, then make sure to
    clean all-qmake-build all to make sure the res is compiled into

    Here is small test project that does it (using your code)

  • Thanks you so much!! After trying your code and seeing that it was almost exactly the same as mine, I figured that it was probably something wrong with the actually project (I might have messed something up) so I made a new project and put all your and my code into it and it worked! I also tried my code and it worked too. So I must have messed something up that I wasn't supposed to. I wouldn't have ever figured that out if it wasn't for your code. Thanks a lot!

Log in to reply