Qt-Qt程序启动时参数处理

.pro
1 QT += core gui 2 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 4 5 CONFIG += c++11 6 7 # The following define makes your compiler emit warnings if you use 8 # any Qt feature that has been marked deprecated (the exact warnings 9 # depend on your compiler). Please consult the documentation of the 10 # deprecated API in order to know how to port your code away from it. 11 DEFINES += QT_DEPRECATED_WARNINGS 12 13 # You can also make your code fail to compile if it uses deprecated APIs. 14 # In order to do so, uncomment the following line. 15 # You can also select to disable deprecated APIs only up to a certain version of Qt. 16 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 17 18 SOURCES += \ 19 main.cpp \ 20 mainwindow.cpp 21 22 HEADERS += \ 23 mainwindow.h 24 25 FORMS += \ 26 mainwindow.ui 27 28 # Default rules for deployment. 29 qnx: target.path = /tmp/$${TARGET}/bin 30 else: unix:!android: target.path = /opt/$${TARGET}/bin 31 !isEmpty(target.path): INSTALLS += target
main.cpp
1 #include "mainwindow.h" 2 3 #include <QApplication> 4 #include <QCommandLineParser> 5 #include <QFileInfo>// 文件信息 6 #include <QDebug> 7 8 int main(int argc, char *argv[]) 9 { 10 QApplication a(argc, argv); 11 a.setApplicationName("MyApp"); // 这对 macOS 很重要,用于匹配 plist 12 13 MainWindow w; 14 w.show(); 15 16 // 处理启动参数 17 // 注意:argv[0] 是程序路径,argv[1] 才是文件路径 18 if (argc > 1) 19 { 20 QString filePath = QString::fromLocal8Bit(argv[1]); 21 QFileInfo fileInfo(filePath); 22 23 if (fileInfo.exists()) 24 { 25 // 调用你的加载文件函数 26 // w.loadFile(filePath); 27 // 我这里是打印 28 qDebug() << "filePath:" << filePath; 29 } 30 } 31 32 return a.exec(); 33 }
作者:疯狂Delphi
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎关注我,一起进步!扫描下方二维码即可加我
浙公网安备 33010602011771号