Minimal Qt console application
Just a quick one for today. Qt is a framework known for its GUI toolkit but it has a lot of niceties that makes programming in C++ more convenient even on console applications. However it can be a bit tricky getting it to work at first and I myself I ended up sticking to this minimum template to get things started in a clean way.
On the main.cpp
file we have:
#include <QCoreApplication>
#include <QThread>
#include <functional>
#include <memory>
// This becomes our main function. Works just
// like a regular main() Only it uses
// QCoreApplication::exit() instead of return
static std::function<void(int, char**)> main_thread =
[](int argc, char** argv)
{
//Write the main() code here
QCoreApplication::exit(0);
};
// The program main creates a thread and launches Qt core
// and will wait until someone calls QCoreApplication::exit()
int main(int argc, char *argv[])
{
int rv;
QCoreApplication a(argc, argv);
std::shared_ptr<QThread> main_qthread (
QThread::create(main_thread, argc, argv)
);
main_qthread->start();
rv = a.exec();
main_qthread->wait();
return rv;
}
And if we are using CMake
instead of qmake
this is the CMakeLists.txt
file, compatible with Qt5 and Qt6:
cmake_minimum_required(VERSION 3.14)
project(my_application LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
#C++17 Required for functional-style thread creation
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED)
add_executable(my_application
main.cpp
)
target_link_libraries(my_application Qt${QT_VERSION_MAJOR}::Core)