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++.

    Thanks.


  • Moderators

    Hi,

    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)
    {
        ui->setupUi(this);
        loadFile&#40;&#41;;
    }
     
    MainWindow::~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
    file.open(QIODevice::ReadOnly);

        QTextStream stream(&file);
        QString line = stream.readAll();
        file.close();
     
        ui->textEdit->setText(line);
    }
    

    @



  • Thank you. That did it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.