一、有时候做项目使用应用程序的绝对路径可能更安全一点,使用绝对路径的方法有两种:1、使用QCoreApplication提供的几个静态函数。2、使用main函数中的argv[0]+QDir。
二、代码:
#include "mainwindow.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QPushButton>
#include <QStringList>
#include <QDebug>
#include <QDir>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
QWidget *pWidget = new QWidget;
w.setCentralWidget(pWidget);
QVBoxLayout *pVBoxLayout = new QVBoxLayout;
QString applicationDirPathStr = QCoreApplication::applicationDirPath();
QString applicationFilePathStr = QCoreApplication::applicationFilePath();
QString applicationNameStr = QCoreApplication::applicationName();
qDebug() << "applicationDirPathStr: " << applicationDirPathStr << "applicationFilePathStr: "
<< applicationFilePathStr << "applicationNameStr: " << applicationNameStr;
QStringList tempList;
tempList.append("applicationDirPathStr:"+applicationDirPathStr);
tempList.append("applicationFilePathStr:"+applicationFilePathStr);
tempList.append("applicationFilePathStr:"+applicationFilePathStr);
QString appPath = argv[0];
QDir appDir(appPath);
QString appName = appDir.dirName();
QString exePath = appPath.left(appPath.length()-appName.length());
qDebug() << "appPath: " << appPath << "appName: " << appName << "exePath: " << exePath;
tempList.append("appPath:"+appPath);
tempList.append("appName:"+appName);
tempList.append("exePath:"+exePath);
foreach(QString str,tempList)
{
QPushButton *pushBtn = new QPushButton(str);
pVBoxLayout->addWidget(pushBtn);
}
pWidget->setLayout(pVBoxLayout);
w.show();
return a.exec();
}
三、运行效果