首先:
QT工程必须在pro文件中加入
LIBS += -lshell32
加入shell32.lib文件,否则工程会报连接出错;
然后在需要用到该功能的头文件里引入两个系统头文件
#include <Windows.h>
#include <ShellAPI.h>
其次:
void inline QOpenDirByFileName(const char* szFileName)
{
//注意事项:1、要加"/select",否则会打开文件;2、编码要转成gb2312
QString strPath(szFileName);
strPath.replace('/','\\');
QString strOpenPath(QString("/select,%1").arg(strPath));
QTextCodec* utf8Codec= QTextCodec::codecForName("utf-8");
QTextCodec* gb2312Codec = QTextCodec::codecForName("gb2312");
QString strUnicode= utf8Codec ->toUnicode(strOpenPath.toStdString().c_str());
QByteArray ByteGb2312= gb2312Codec ->fromUnicode(strUnicode);
LPCSTR filePath = ByteGb2312.data();
ShellExecuteA(0,"open","explorer.exe",filePath, NULL, true);
}