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 }

 

posted on 2026-02-07 04:59  疯狂delphi  阅读(0)  评论(0)    收藏  举报

导航