Trying to open file dialog with Qt

Viewed 794

I'm trying to write a simple C++ code using Qt to grab the path to a folder.

I got the code from this answer and tweaked it a bit to fit what I wanted. My problem is that it's flagging my 'this' declaration saying my class is incompatible with the 'QWidget *' parameter type.

#include <iostream>
#include <qt5/QtWidgets/qfiledialog.h>

using namespace std;

class TCC {
public:
    string openFile();
};

string TCC::openFile()
{
    QFileDialog::getOpenFileName(this, tr("Open Document"), QDir::currentPath(), tr("Document files (*.doc *.rtf);;All files (*.*)"), 0, QFileDialog::DontUseNativeDialog);

    QString filename = QFileDialog::getOpenFileName(
        this,
        tr("Open Document"),
        QDir::currentPath(),
        tr("Document files (*.doc *.rtf);;All files (*.*)"));
    if (!filename.isNull())
    {
        qDebug(filename.toUtf8());
    }
    return filename.toUtf8().constData();
}

int main()
{
    TCC tcc;
    cout << tcc.openFile();
}
1 Answers

There are several errors in your code:

  1. QFileDialog requires a QWidget or a nullptr as the first argument.
  2. tr() is a QObject method, since there is none, you must use QObject::tr().
  3. To convert QString to std::string you must use the toStdString() method.
  4. Any QWidget(like QFileDialog) requires a QApplication to have been created before.
#include <QApplication>
#include <QFileDialog>

#include <iostream>

class TCC {
public:
    std::string openFile();
};

std::string TCC::openFile()
{
    QString filename = QFileDialog::getOpenFileName(
                nullptr,
                QObject::tr("Open Document"),
                QDir::currentPath(),
                QObject::tr("Document files (*.doc *.rtf);;All files (*.*)"));
    return filename.toStdString();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    TCC tcc;
    std::cout << tcc.openFile()<< std::endl;

    return EXIT_SUCCESS;
}
Related