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

1

I have in a code that makes a listing of teachers with their proper graduations that is stored with the txt file, making due opening with variable ifstream, using open with the name of the file on disk. So I call the class constructor in mainwindow.cpp like this:

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

Soon this will be the last parameter to open open my file, but obviously this has to be done previously in the code, and I would like to know how the user, when clicking a button, open the directory for there user to select the desired file and open it if it is valid.

    
asked by anonymous 23.11.2015 / 20:10

1 answer

1

I suggested using the 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, clicking the "Open File" button will open a new window where the user can select a file. The path to the file will then be placed in LineEdit.

    
23.11.2015 / 22:53