參考:
Compiling your first Qt Program in Ubuntu
Vscode開發Qt
Visual Studio Code開發Qt應用程序實現自動提示、語法高亮、代碼導航、編譯和調試
安裝環境
- In order to install the Build Essential package:
$ sudo apt-get install build-essential
- In order to install the Qt Creator package that contains both the UI and command line tools for Qt project creation and execution:
$ sudo apt-get install qtcreator
- If you want Qt 5 to be used as the default Qt Creator version, then run the following command:
$ sudo apt install qt5-default
- Install the Qt documentation and examples:
$ sudo apt-get install qt5-doc qtbase5-examples qtbase5-doc-html
vscode 配置
- 創建目錄做爲workspace,就叫qt吧。
- 按照指引或手動創建配置文件,以實現代碼導航
- .vscode/c_cpp_properties.json:
{ "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/include/x86_64-linux-gnu/qt5/QtWidgets", "/usr/include/x86_64-linux-gnu/qt5/*" ], "defines": [], "compilerPath": "/usr/bin/clang", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "clang-x64" } ], "version": 4 }
- .vscode/c_cpp_properties.json:
- 創建cpp文件
- testmain.cpp:
#include <QApplication> #include <QLabel> #include <QWidget> int main(int argc, char *argv[]) { QApplication app(argc, argv); QLabel hello("<center>Welcome to my first Qt program</center>"); hello.setWindowTitle("My First Qt Program"); hello.resize(400, 400); hello.show(); return app.exec(); }
- testmain.cpp:
- 使用qmake生成qt工程
$ qmake -project
會生成一個qt.pro文件,文件名規則是 ‘工程目錄名’.pro 。
其中有一行聲明瞭目標文件:TARGET = qt
。
我們在裏面添加一行:QT += gui widgets
應該是聲明依賴的作用。 - 使用qmake生成Makefile
$ qmake qt.pro
- 編譯
$ make
即可生成可執行文件,文件名是pro文件制定的TARGET。 - 運行一下看看
$ chmod +x qt && ./qt
,會彈出一個窗口:
- 使用vscode的run功能:
- 新建 launch.json 文件:
其中有一行{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/qt", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "Build" } ] }
"preLaunchTask": "Build"
, 這個Build會在tasks.json文件裏找定義。 - 新建 tasks.json 文件
這時就可以在vscode的run中點擊運行了。{ "version": "2.0.0", "tasks": [ { "label": "Build", // build任務 "type": "shell", // "command": "make -f Makefile" "command" : "qmake" } ] }
- 新建 launch.json 文件:
- 看下現在的目錄結構:
├── Makefile ├── .qmake.stash ├── qt ├── qt.pro ├── testmain.cpp ├── testmain.o └── .vscode ├── c_cpp_properties.json ├── launch.json ├── settings.json // 沒啥意義,vscode提示自動生成的 └── tasks.json 1 directory, 10 files