如何在C++中调用 QDir 库

How can I call a QDir lib in C++?

本文关键字:调用 QDir C++      更新时间:2023-10-16

我在计算机中下载了qt,并称QDir为#include<QDir>。但它提出了错误fatal error: QDir: No such file or directory.有没有办法在不创建 .pro 文件的情况下使用 QDir?

我尝试创建一个 .pro 文件:

Template += app 
QT += core
Source += src.cpp

但它不起作用

#include <QDir>
src.cpp:1:16: fatal error: QDir: No such file or directory

构建src.cpp的最小.pro文件,假设您在那里也有main功能:

SOURCES += src.cpp

请使用Qt Creator新项目向导为您创建.pro文件(或CMake的cmakelist.txt(,或使用已知良好的示例/模板开始,以便您一切正确。您不想在没有生成文件生成器的情况下使用像Qt这样的复杂框架!但是,如果您确实必须使用qmake(或cmake(生成一次makefile,然后删除.pro文件并继续编辑makefile。请注意,如果没有很多额外的工作,它可能不适用于除您之外的任何人。所以不要去那里。


使用QDir做一些事情的完整工作示例:

.pro 文件:

# core and gui are defaults, remove gui
QT -= gui
# cmdline includes console for Win32, and removes app_bundle for Mac
CONFIG += cmdline
# there should be no reason to not use C++14 today
CONFIG += c++14
# enable more warnings for compiler, remember to fix them
CONFIG += warn_on
# this is nice to have
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp

示例主.cpp

#include <QDir>
#include <QDebug> // or use std::cout etc
//#include <QCoreApplication>
int main(int argc, char *argv[])
{
    // for most Qt stuff, you need the application object created,
    // but this example works without
    //QCoreApplication app(argc, argv);
    for(auto name : QDir("/").entryList()) {
        qDebug() << name;
    }
    // return app.exec(); // don't start event loop (main has default return 0)
}