QT Creator - How to open a window with directories for the user to select text file ? C++

Asked

Viewed 1,228 times

1

I have in a code that makes a list of teachers with their due degrees that is stored with the txt file, making the proper opening with variable ifstream, using open with the name of the file on the disk. So I call the class builder in mainwindow.cpp so :

TP2::ProfessorDAO teste("/Users/eugeniojulio/Documents/2015/PUC_2015/PUC_2015_2/TP2/ArquivoDeDados.csv");

then this will be the parameter passed to open my file, but obviously this has to be done previously in the code, and I would like to know the way the user , by clicking a button, open the directory so that the user selects the desired file and open itor, if valid.

1 answer

1

I suggested the use of class Qfiledialog. This class provides a dialog box that allows the user to choose a file or directory.

Here is a small example:

#include <QApplication>
#include <QPushButton>
#include <QLineEdit>
#include <QFileDialog>

class Window : public QWidget {
    Q_OBJECT
public:
    explicit Window(QWidget *parent = 0);
private slots:
    void buttonClicked();
private:
    QPushButton *button_;
    QLineEdit *lineEdit_;
};

#include "main.moc"

Window::Window(QWidget *parent) : QWidget(parent) { 
    setFixedSize(100, 50);

    button_ = new QPushButton("Abrir ficheiro", this);
    button_->setGeometry(10, 10, 90, 30);
    button_->setCheckable(true);

    lineEdit_ = new QLineEdit(this);
    lineEdit_->setGeometry (10, 40, 180, 30);

    connect(button_, SIGNAL (clicked(bool)), this, SLOT (buttonClicked()));
}

void Window::buttonClicked() {
    QString filename = QFileDialog::getOpenFileName(this, tr("Abrir ficheiro"), "/home/bruno", tr("Text files (*.txt)"));

    lineEdit_->setText(filename);
}

int main (int argc, char **argv) {
    QApplication app (argc, argv);

    Window window;
    window.setFixedSize (200, 80);
    window.show ();

    return app.exec ();
}

In this example, by clicking the "Open File" button a new window will be shown where the user can select a file. The path (path) to the file will then be placed in Lineedit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.