c++ - 尝试用 Qt 打开文件对话框

标签 c++ qt visual-c++

我正在尝试使用 Qt 编写一个简单的 C++ 代码来获取文件夹的路径。

我从 this 得到代码回答并稍微调整一下以适应我想要的。我的问题是它标记了我的“this”声明,说我的类与“QWidget *”参数类型不兼容。

#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. QFileDialog 需要一个 QWidget 或一个 nullptr 作为第一个参数。
  2. tr() 是一个 QObject 方法,既然没有,你必须使用 QObject::tr()
  3. 要将 QString 转换为 std::string,您必须使用 toStdString() 方法。
  4. 任何 QWidget(如 QFileDialog)都需要一个 QApplication 之前已经创建。
#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;
}

关于c++ - 尝试用 Qt 打开文件对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68968316/

相关文章:

visual-studio - Visual Studio Profiler 将 "[broken]"显示为函数名称

c++ - 如何实现 split 函数来分割一行中的单词?

c++ - 如何创建自定义 Murmur Avalanche 混合器?

c++ - 如何将 zlib 添加到现有的 qt 安装

qt - 为什么我们应该总是从 Qt 中的基类派生?

c++ - 双击QWidget

c++ - 我怎样才能让我的 QThread 阻塞并等待从主线程调用的函数返回一个值?

c++ - 如何获取文件信息?

c++ - Eigen 3 断言在求解线性系统时失败 - 据我所知,这是由于 Eigen 中的无效索引造成的

c++ - 在 C++ 中设置 var 的语法