Copy a file to build directory after compiling project with Qt

后端 未结 6 1795
孤街浪徒
孤街浪徒 2020-12-13 06:36

I have seen several suggestions, but nothing really worked for me as I want. I just need to copy a file to the desired destination directory.

Say, for example from t

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 07:14

    Having had the pleasure of wasting a few hours with this, i thought i'd share my findings on the matter. This in a modified variant of Paglian's method here. Since i'm using windows (without mingw) that method doesn't work. So here is the modified variant:

    # using shell_path() to correct path depending on platform
    # escaping quotes and backslashes for file paths
    copydata.commands = $(COPY_FILE) \"$$shell_path($$PWD\\archive.png)\" \"$$shell_path($$OUT_PWD)\"
    first.depends = $(first) copydata
    export(first.depends)
    export(copydata.commands)
    QMAKE_EXTRA_TARGETS += first copydata
    

    Since this makes it cross platform you could of course also use this method in Linux, MacOS or what have you. Do note that i'm copying a single file, so instead of $(COPY_DIR) i'm using $(COPY_FILE). Adapt as needed.


    If you want the file(s) copied to the exact path of where the binary ends up (since the binary will end up in a subfolder of $$OUT_PWD (debug or release, at least when building with Qt Creator with MSVC 14/cdb.exe/Code::Blocks Makefiles configuration) you need this:

    # adapted from https://stackoverflow.com/a/2581068
    CONFIG(debug, debug|release) {
        VARIANT = debug
    } else {
        VARIANT = release
    }
    

    Beware that even though the binary ends up in a subfolder, QtCreator executes the binary from $$OUT_PWD, so it expects to find file resources in $$OUT_PWD, and NOT the debug subdir. That means you for example can't do QIcon("archive.png") and expect it to find it besides the executable.

    This is of course easy to remedy by doing:

    QDir exeDir(QCoreApplication::applicationDirPath());
    QIcon qIcon(exeDir.filePath("archive.png"));
    

    IF you decide this is what you want, you obviously need to edit the last argument of $$(COPY_FILE) (in .pro) like this: \"$$shell_path($$OUT_PWD)\\$$VARIANT\"


    One other thing to note is that (in my case anyway) Qt Creator (4.0.1) doesn't always build the .pro file, since it's not detecting any changes in the configuration, so to have the above changes reflected in the Makefile (and thus run when you build your project) you have to actually build the .pro manually by running Build->run qmake from the application menu. To ensure everything goes smooth, look as the compile output by hitting Alt+4 (on Windows anyway).

提交回复
热议问题