Important: Please read the Qt Code of Conduct -

I would like to open and read a text file at program launch, using Qt

  • I would like to open a text file at program launch, using Qt. I would like the text to appear in the text field which is called textEdit.

    It is a simple notepad program that I am changing into an app I want to do other special things.

    How do I input a text file, say "text.txt" into my textEdit widget upon program launch? All of the text file.

    Writing with C++.


  • Moderators


    You can open and read the file from your QMainWindow or QDialog's constructor.
    Try the following code:
    @ #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QFile>
    #include <QTextStream>

    MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
        ui(new Ui::MainWindow)
        delete ui;
    void MainWindow::loadFile&#40;&#41;
        QFile file&#40;":/read.txt"&#41;; //If present in Resource 

    // QFile file("D:/Test/read.txt"); //If present on system;

        QTextStream stream(&file);
        QString line = stream.readAll();


  • Thank you. That did it.

Log in to reply