Реализация библиотеки и приложения для демонстрации

main
Евгений Тетерин 2025-07-21 14:56:33 +03:00
parent 5cc077b3c8
commit 78b5476af2
42 changed files with 1988 additions and 1 deletions

107
.gitignore vendored 100644
View File

@ -0,0 +1,107 @@
.build/
_other/
_distrib*/
# Tmp files
*~
Thumbs.db*
# C++ objects and libs
*.slo
*.lo
*.o
*.a
*.la
*.lai
*.so
*.so.*
*.dll
*.dylib
*.ko
*.obj
*.elf
*.lib
# Qt-es
object_script.*.Release
object_script.*.Debug
*_plugin_import.cpp
/.qmake.cache
/.qmake.stash
*.pro.user
*.pro.user.*
*.qbs.user
*.qbs.user.*
*.moc
moc_*.cpp
moc_*.h
qrc_*.cpp
ui_*.h
*.qmlc
*.jsc
Makefile*
*build-*
*.qm
*.prl
# Qt unit tests
target_wrapper.*
# QtCreator
*.autosave
# QtCreator Qml
*.qmlproject.user
*.qmlproject.user.*
# QtCreator CMake
CMakeLists.txt.user*
# QtCreator 4.8< compilation database
compile_commands.json
# QtCreator local machine specific files for imported projects
*creator.user*
*_qmlcache.qrc
# ---> C
# Prerequisites
*.d
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
# Fortran module files
*.mod
*.smod

10
CMakeLists.txt 100644
View File

@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project (QtCircularMenuExample)
# Circular menu library:
add_subdirectory(lib_circular_menu)
# Example Application:
add_subdirectory(application)

9
LICENSE 100644
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

25
LICENSE.ru 100644
View File

@ -0,0 +1,25 @@
MIT лицензия
Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
Данная лицензия разрешает лицам, получившим копию
данного программного обеспечения и сопутствующей документации
(в дальнейшем именуемыми «Программное Обеспечение»), безвозмездно
использовать Программное Обеспечение без ограничений,
включая неограниченное право на использование, копирование, изменение,
слияние, публикацию, распространение, сублицензирование и/или продажу
копий Программного Обеспечения, а также лицам, которым предоставляется
данное Программное Обеспечение, при соблюдении следующих условий:
Указанное выше уведомление об авторском праве и данные условия
должны быть включены во все копии или значимые части данного Программного Обеспечения.
ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ»,
БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ,
ВКЛЮЧАЯ ГАРАНТИИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ
НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ.
НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ
ПО КАКИМ-ЛИБО ИСКАМ, ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ ЧИСЛЕ,
ПРИ ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ СИТУАЦИИ,
ВОЗНИКШИМ ИЗ-ЗА ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
ИЛИ ИНЫХ ДЕЙСТВИЙ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.

View File

@ -1,3 +1,27 @@
# Qt_Circular_Menu_Example
Пример реализации кругового меню на Qt Widgets
Пример реализации кругового меню на Qt Widgets
## Реализация
Меню реализовано в виде отдельного виджета в библиотеке `lib_circular_menu`.
Для применения в программе необходимо создать экземпляр класса `CircularMenu` и назначить список пунктов меню:
```
#include "circular_menu.h"
...
QList<QAction*> menuActions; // заполнить список
...
CircularMenu *circularMenu = new CircularMenu(this); // родитель обязательно виджет
circularMenu->addActions(menuActions);
circularMenu->setHotKey(Qt::Key_Alt);
```
## Внешний вид (Qt6, ОС Windows 11)
![picture](/_resources/images/screenshot.png)

View File

@ -0,0 +1,28 @@
# Файл для подключения в основной проект через include
# Настройки для приложений
include(${CMAKE_CURRENT_LIST_DIR}/common.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/developer.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/version.cmake)
# Имя выходного файла совпадает с названием проекта:
set(RUNTIME_OUTPUT_NAME ${PROJECT_NAME})
configure_file(
${CMAKE_CURRENT_LIST_DIR}/config.h.in
${CMAKE_CURRENT_BINARY_DIR}/config.h
@ONLY
)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${DISTRIB_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${DISTRIB_DIR})
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
configure_file(
${CMAKE_CURRENT_LIST_DIR}/versioninfo.rc.in
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
@ONLY
)
endif()

View File

@ -0,0 +1,52 @@
# Общие настройки для всех типов проектов
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
if (CMAKE_COMPILER_IS_GNUCXX)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "9.0.0")
set(CMAKE_CXX_STANDARD 20)
else()
set(CMAKE_CXX_STANDARD 23)
endif()
else()
set(CMAKE_CXX_STANDARD 23)
endif()
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Поиск библиотек Qt:
find_package(QT NAMES Qt6 Qt5 REQUIRED)
# Настройки каталогов:
include(${CMAKE_CURRENT_LIST_DIR}/setup_directories.cmake)
# Определение разрядности:
if (${CMAKE_SIZEOF_VOID_P} STREQUAL 4)
set(DIR_PREFIX "32")
elseif (${CMAKE_SIZEOF_VOID_P} STREQUAL 8)
set(DIR_PREFIX "64")
endif ()
# Каталог для готовых приложений и библиотек после компиляции:
set(DISTRIB_DIR
${ROOT_PROJECT_DIR}_distrib/${CMAKE_SYSTEM_NAME}_Qt${QT_VERSION}_${DIR_PREFIX}-bit
)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(IS_DEBUG TRUE)
set(IS_RELEASE FALSE)
else()
set(IS_DEBUG FALSE)
set(IS_RELEASE TRUE)
endif()
message(STATUS "Project '${PROJECT_NAME}' compiler ${CMAKE_CXX_COMPILER} version: ${CMAKE_CXX_COMPILER_VERSION}")
message(STATUS "Project '${PROJECT_NAME}' distrib dir: '${DISTRIB_DIR}'")
message(STATUS "Project '${PROJECT_NAME}' IS_RELEASE: ${IS_RELEASE}, IS_DEBUG: ${IS_DEBUG}")
message(STATUS "Project '${PROJECT_NAME}' CMAKE_PREFIX_PATH: '${CMAKE_PREFIX_PATH}'")
message(STATUS "Project '${PROJECT_NAME}' CMAKE_SYSTEM_LIBRARY_PATH: '${CMAKE_SYSTEM_LIBRARY_PATH}'")

View File

@ -0,0 +1,9 @@
#define PROG_NAME "@PROJECT_NAME@"
#define PROG_VERSION "@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.@BUILD_NUM@@PROJECT_VERSION_TWEAK@"
#define PROG_CAPTION "@PROJECT_NAME@ v"
#define PROG_DESCRIPTION "@PROJECT_DESCRIPTION@"
#define SOFT_DEVELOPER "@SOFT_DEVELOPER@"
#define DEVELOPER_DOMAIN "@DEVELOPER_DOMAIN@"
#define BUILD_DATE "@BUILD_DATE@"
#define BUILD_NUM "@BUILD_NUM@"
#define ORIGINAL_FILE_NAME "@ORIGINAL_FILE_NAME@"

View File

@ -0,0 +1,289 @@
# Определение зависимостей после сборки приложения
cmake_minimum_required(VERSION 4.0)
set(LIBS_FIND_DIRS "${PREFIX}")
set(QT_SHARE_DIR "${PREFIX}")
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
if (EXISTS "${PREFIX}/bin")
set(LIBS_FIND_DIRS "${PREFIX}/bin")
endif()
else()
if (EXISTS "${PREFIX}/lib")
set(LIBS_FIND_DIRS "${PREFIX}/lib")
endif()
endif()
if (EXISTS "${PREFIX}/share/qt${QT_VERSION_MAJOR}")
set(QT_SHARE_DIR "${PREFIX}/share/qt${QT_VERSION_MAJOR}")
endif()
if(TARGET_TYPE STREQUAL "EXECUTABLE")
if (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}")
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}")
elseif (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}.exe")
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}.exe")
endif()
else()
if (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}")
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}")
elseif (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}.dll")
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}.dll")
elseif (EXISTS "${OUTPUT_DIR}/${TARGET_NAME}.so")
set(TARGET_FILE "${OUTPUT_DIR}/${TARGET_NAME}.so")
endif()
endif()
message(STATUS "TARGET_FILE: '${TARGET_FILE}'")
message(STATUS "LIBS_FIND_DIRS: '${LIBS_FIND_DIRS}'")
message(STATUS "OUTPUT_DIR: '${OUTPUT_DIR}'")
message(STATUS "QT_VERSION_MAJOR: '${QT_VERSION_MAJOR}'")
message(STATUS "Find and copy dependencies. Please, wait...")
# functions --------------------------------------------------------------------
# Копирование файла
function(safe_copy src dest)
# Пытаемся скопировать через execute_process (кросс-платформенно)
execute_process(
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${src}" "${dest}"
RESULT_VARIABLE copy_result
ERROR_VARIABLE copy_error
OUTPUT_QUIET # Подавляем stdout
)
if(NOT copy_result EQUAL 0)
message(WARNING "Не удалось скопировать ${src} -> ${dest}: ${copy_error}")
return()
endif()
endfunction()
# Отслеживание цепочки ссылок
function(get_symlink_chain dep symlink_chain)
unset(chain)
set(current_dep "${dep}")
# 1. Разрешаем основную цепочку симлинков (исходный файл конечный файл)
while(IS_SYMLINK "${current_dep}")
execute_process(
COMMAND readlink "${current_dep}"
OUTPUT_VARIABLE link_target
OUTPUT_STRIP_TRAILING_WHITESPACE
)
list(INSERT chain 0 "${current_dep}") # Добавляем текущий симлинк в начало
get_filename_component(parent_dir "${current_dep}" DIRECTORY)
set(current_dep "${parent_dir}/${link_target}") # Переходим по ссылке
endwhile()
# 2. Добавляем конечный файл в начало цепочки
list(INSERT chain 0 "${current_dep}")
# 3. Теперь ищем ВСЕ симлинки в этой директории, которые ссылаются на конечный файл
if(EXISTS "${current_dep}")
get_filename_component(final_file "${current_dep}" REALPATH) # Абсолютный путь конечного файла
get_filename_component(parent_dir "${current_dep}" DIRECTORY) # Директория конечного файла
# Получаем список всех файлов в этой директории
file(GLOB all_files LIST_DIRECTORIES false "${parent_dir}/*")
foreach(file IN LISTS all_files)
# Если это симлинк, проверяем, ведёт ли он на конечный файл
if(IS_SYMLINK "${file}")
execute_process(
COMMAND readlink -f "${file}" # Абсолютный путь цели симлинка
OUTPUT_VARIABLE symlink_target
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# Если цель симлинка совпадает с конечным файлом, добавляем в цепочку
if(symlink_target STREQUAL final_file AND NOT file IN_LIST chain)
list(APPEND chain "${file}")
endif()
endif()
endforeach()
endif()
set(${symlink_chain} "${chain}" PARENT_SCOPE)
endfunction()
# ------------------------------------------------------------------------------
if (EXISTS "${TARGET_FILE}")
# Получаем runtime-зависимости
file(GET_RUNTIME_DEPENDENCIES
EXECUTABLES ${TARGET_FILE}
RESOLVED_DEPENDENCIES_VAR RESOLVED_DEPS
UNRESOLVED_DEPENDENCIES_VAR UNRESOLVED_DEPS
DIRECTORIES ${LIBS_FIND_DIRS}
)
set(USE_SQL OFF)
set(USE_PRINT OFF)
set(USE_NETWORK OFF)
set(USE_SERIALPORT OFF)
set(USE_MULTIMEDIA OFF)
message(STATUS "\nResolved dependencies copy:\n")
foreach(DEP ${RESOLVED_DEPS})
string(FIND "${DEP}" "${LIBS_FIND_DIRS}" POS)
if(POS EQUAL 0)
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
message(STATUS "${DEP}")
file(COPY "${DEP}" DESTINATION "${OUTPUT_DIR}")
else ()
#message(STATUS "${DEP}")
#file(COPY "${DEP}" DESTINATION "${OUTPUT_DIR}/system_lib" FOLLOW_SYMLINK_CHAIN)
get_symlink_chain("${DEP}" dep_chain)
foreach(file IN LISTS dep_chain)
message(STATUS "${file}")
safe_copy("${file}" "${OUTPUT_DIR}")
endforeach()
endif()
endif()
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Sql" POS)
if(POS GREATER 0)
set(USE_SQL ON)
endif()
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Print" POS)
if(POS GREATER 0)
set(USE_PRINT ON)
endif()
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Network" POS)
if(POS GREATER 0)
set(USE_NETWORK ON)
endif()
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Serial" POS)
if(POS GREATER 0)
set(USE_SERIALPORT ON)
endif()
string(FIND "${DEP}" "Qt${QT_VERSION_MAJOR}Multimedia" POS)
if(POS GREATER 0)
set(USE_MULTIMEDIA ON)
endif()
endforeach()
if (EXISTS "${LIBS_FIND_DIRS}/libQt${QT_VERSION_MAJOR}XcbQpa.so")
get_symlink_chain("${LIBS_FIND_DIRS}/libQt${QT_VERSION_MAJOR}XcbQpa.so" xcb_chain)
foreach(file IN LISTS xcb_chain)
message(STATUS "${file}")
safe_copy("${file}" "${OUTPUT_DIR}")
endforeach()
endif()
message(STATUS "\nResolved dependencies not copy:\n")
foreach(DEP ${RESOLVED_DEPS})
string(FIND "${DEP}" "${LIBS_FIND_DIRS}" POS)
if(NOT POS EQUAL 0)
message(STATUS "${DEP}")
endif()
endforeach()
message(STATUS "\nUnresolved dependencies:\n")
foreach(DEP ${UNRESOLVED_DEPS})
message(STATUS "${DEP}")
endforeach()
if (EXISTS "${QT_SHARE_DIR}/plugins/platforms")
file(COPY "${QT_SHARE_DIR}/plugins/platforms" DESTINATION "${OUTPUT_DIR}")
endif()
if (EXISTS "${QT_SHARE_DIR}/plugins/platformthemes")
file(COPY "${QT_SHARE_DIR}/plugins/platformthemes" DESTINATION "${OUTPUT_DIR}")
endif()
if (EXISTS "${QT_SHARE_DIR}/plugins/styles")
file(COPY "${QT_SHARE_DIR}/plugins/styles" DESTINATION "${OUTPUT_DIR}")
endif()
if (EXISTS "${QT_SHARE_DIR}/plugins/imageformats")
file(COPY "${QT_SHARE_DIR}/plugins/imageformats" DESTINATION "${OUTPUT_DIR}")
endif()
if (USE_SQL AND (EXISTS "${QT_SHARE_DIR}/plugins/sqldrivers"))
file(COPY "${QT_SHARE_DIR}/plugins/sqldrivers" DESTINATION "${OUTPUT_DIR}")
endif()
if (USE_PRINT AND (EXISTS "${QT_SHARE_DIR}/plugins/printsupport"))
file(COPY "${QT_SHARE_DIR}/plugins/printsupport" DESTINATION "${OUTPUT_DIR}")
endif()
if (USE_NETWORK AND (EXISTS "${QT_SHARE_DIR}/plugins/networkinformation"))
file(COPY "${QT_SHARE_DIR}/plugins/networkinformation" DESTINATION "${OUTPUT_DIR}")
endif()
if (USE_MULTIMEDIA AND (EXISTS "${QT_SHARE_DIR}/plugins/multimedia"))
file(COPY "${QT_SHARE_DIR}/plugins/multimedia" DESTINATION "${OUTPUT_DIR}")
endif()
if (EXISTS "${QT_SHARE_DIR}/translations")
file(MAKE_DIRECTORY "${OUTPUT_DIR}/translations")
if (EXISTS "${QT_SHARE_DIR}/translations/qtbase_ru.qm")
file(COPY "${QT_SHARE_DIR}/translations/qtbase_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
endif()
if (EXISTS "${QT_SHARE_DIR}/translations/qtdeclarative_ru.qm")
file(COPY "${QT_SHARE_DIR}/translations/qtdeclarative_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
endif()
if (USE_SERIALPORT AND (EXISTS "${QT_SHARE_DIR}/translations/qtserialport_ru.qm"))
file(COPY "${QT_SHARE_DIR}/translations/qtserialport_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
endif()
if (USE_MULTIMEDIA AND (EXISTS "${QT_SHARE_DIR}/translations/qtmultimedia_ru.qm"))
file(COPY "${QT_SHARE_DIR}/translations/qtmultimedia_ru.qm" DESTINATION "${OUTPUT_DIR}/translations")
endif()
endif()
else()
message(STATUS "'${TARGET_FILE}' not found. Exit.")
endif()

View File

@ -0,0 +1,8 @@
if(NOT DEFINED SOFT_DEVELOPER OR "${SOFT_DEVELOPER}" STREQUAL "")
set(SOFT_DEVELOPER "Evgeny Teterin")
endif()
if(NOT DEFINED DEVELOPER_DOMAIN OR "${DEVELOPER_DOMAIN}" STREQUAL "")
set(DEVELOPER_DOMAIN "poseon.ru")
endif()

View File

@ -0,0 +1,29 @@
# Файл для подключения в основной проект через include
# Настройки для библиотек
include(${CMAKE_CURRENT_LIST_DIR}/common.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/developer.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/version.cmake)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${DISTRIB_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${DISTRIB_DIR})
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
set(RUNTIME_OUTPUT_NAME lib${PROJECT_NAME}.dll)
configure_file(
${CMAKE_CURRENT_LIST_DIR}/versioninfo.rc.in
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
@ONLY
)
else()
set(RUNTIME_OUTPUT_NAME lib${PROJECT_NAME}.so)
endif()
configure_file(
${CMAKE_CURRENT_LIST_DIR}/config.h.in
${CMAKE_CURRENT_BINARY_DIR}/config.h
@ONLY
)

View File

@ -0,0 +1,40 @@
# Файл для подключения в основной проект через include
# Вспомогательные действия после сборки проекта
if(IS_DEBUG)
message(STATUS "Project '${PROJECT_NAME}' [post-build] DEBUG building: skip post-build actions")
return()
endif()
# Включение/выключение поиска зависимостей:
set(COPY_DEPENDS ON)
get_target_property(TARGET_TYPE ${PROJECT_NAME} TYPE)
if(TARGET_TYPE STREQUAL "EXECUTABLE")
message(STATUS "${PROJECT_NAME} is an executable.")
elseif(TARGET_TYPE STREQUAL "STATIC_LIBRARY" OR TARGET_TYPE STREQUAL "SHARED_LIBRARY")
message(STATUS "${PROJECT_NAME} is a library.")
else()
message(STATUS "${PROJECT_NAME} is of another type: ${TARGET_TYPE}")
endif()
if (COPY_DEPENDS)
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E echo "Copying runtime dependencies..."
COMMAND ${CMAKE_COMMAND}
-DTARGET_NAME="${RUNTIME_OUTPUT_NAME}"
-DTARGET_TYPE="${TARGET_TYPE}"
-DOUTPUT_DIR="${DISTRIB_DIR}"
-DPREFIX="${CMAKE_PREFIX_PATH}"
-DQT_VERSION_MAJOR=${QT_VERSION_MAJOR}
-DCMAKE_SYSTEM_NAME="${CMAKE_SYSTEM_NAME}"
-P "${CMAKE_INC_DIR}/copy_depends.cmake"
COMMENT "Copying runtime dependencies for ${PROJECT_NAME}"
)
endif()

View File

@ -0,0 +1,25 @@
set(ROOT_PROJECT_DIR
${CMAKE_CURRENT_LIST_DIR}/..
)
cmake_path(NORMAL_PATH ROOT_PROJECT_DIR OUTPUT_VARIABLE ROOT_PROJECT_DIR)
set(CMAKE_INC_DIR
${ROOT_PROJECT_DIR}_cmake
)
set(RESOURCES_DIR
${ROOT_PROJECT_DIR}_resources
)
set(COMMON_SOURCES_DIR
${ROOT_PROJECT_DIR}_include
)
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
set(SYSTEM_INCLUDE_DIR "${CMAKE_PREFIX_PATH}/include")
else ()
set(SYSTEM_INCLUDE_DIR "/usr/include")
endif ()

View File

@ -0,0 +1,55 @@
# Файл для подключения в основной проект через include
# Настройки компиляции для всего
if (DISABLE_HARD_WARNING_ERROR)
target_compile_options(${PROJECT_NAME} PRIVATE
-Wall
-Wextra
-Wpedantic
)
else()
target_compile_options(${PROJECT_NAME} PRIVATE
-Wall # Все стандартные предупреждения
-Wextra # Дополнительные предупреждения
-Wpedantic # Соответствие стандарту C++
-Werror # Превратить предупреждения в ошибки
-Wconversion # Предупреждения о неявных преобразованиях
-Wsign-conversion # Предупреждения о знаковых/беззнаковых преобразованиях
-Wshadow # Предупреждения о "тенях" переменных
-Wunused # Предупреждения о неиспользуемом коде
-Wold-style-cast # Запрет C-style кастов (только static_cast/dynamic_cast/...)
-Wnull-dereference # Предупреждения о возможных разыменованиях nullptr
-Wdouble-promotion # Предупреждения о неявном преобразовании float double
-Wformat=2 # Строгая проверка printf/scanf
)
endif()
target_compile_definitions(${PROJECT_NAME} PRIVATE
QT_NO_FOREACH
QT_NO_URL_CAST_FROM_STRING
QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
QT_STRICT_ITERATORS
)
find_program(CLANG_TIDY_EXE NAMES "clang-tidy")
if (CLANG_TIDY_EXE)
set(CMAKE_CXX_CLANG_TIDY "${CLANG_TIDY_EXE};-checks=*")
endif()
if (CMAKE_BUILD_TYPE STREQUAL "Debug" OR CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
target_compile_options(${PROJECT_NAME} PRIVATE
-fsanitize=address # AddressSanitizer (поиск утечек, выходов за границы)
-fsanitize=undefined # UndefinedBehaviorSanitizer (UB-проверки)
-fsanitize=leak # LeakSanitizer (поиск утечек памяти)
-fno-omit-frame-pointer # Для лучшего стека вызовов в санитайзерах
)
target_link_options(${PROJECT_NAME} PRIVATE
-fsanitize=address
-fsanitize=undefined
-fsanitize=leak
)
endif()

View File

@ -0,0 +1,70 @@
# Файл для подключения в основной проект через include
# Обновление и генерация файлов переводов
# Языки переводов перечислить в переменной LNG
if(IS_DEBUG)
message(STATUS "Project '${PROJECT_NAME}' [translations] DEBUG building: skip .qm generation")
return()
endif()
# Если список языков не задан в основном CMakeLists.txt применяем по умолчанию
if(NOT DEFINED LNG)
set(LNG en ru)
message(STATUS "Project '${PROJECT_NAME}' [translations] LNG not set, use default: ${LNG}")
else()
message(STATUS "Project '${PROJECT_NAME}' [translations] Use LNG: ${LNG}")
endif()
# Подключить LinguistTools
find_package(Qt${QT_VERSION_MAJOR}LinguistTools REQUIRED)
# Полные пути утилит
get_target_property(LUPDATE_EXECUTABLE Qt${QT_VERSION_MAJOR}::lupdate IMPORTED_LOCATION)
get_target_property(LRELEASE_EXECUTABLE Qt${QT_VERSION_MAJOR}::lrelease IMPORTED_LOCATION)
# Каталог генерации файлов ts и qm файлов
set(TRANSLATIONS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/translations")
set(QM_OUTPUT_DIR "${DISTRIB_DIR}/translations")
file(MAKE_DIRECTORY "${TRANSLATIONS_DIR}")
file(MAKE_DIRECTORY "${QM_OUTPUT_DIR}")
# Список TS файлов в зависимости от списка языков
set(TS_FILES "")
# Обновление каждого файла с добавлением в список
foreach(LANG ${LNG})
set(TS_FILE "${TRANSLATIONS_DIR}/${PROJECT_NAME}_${LANG}.ts")
list(APPEND TS_FILES "${TS_FILE}")
message(STATUS "Project '${PROJECT_NAME}' Update translation file: ${TS_FILE}")
execute_process(COMMAND ${LUPDATE_EXECUTABLE}
${PROJECT_SOURCES}
-ts ${TS_FILE}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
endforeach()
# Генерация файлов qm
set(QM_FILES "")
foreach(TS ${TS_FILES})
get_filename_component(TS_NAME_WE ${TS} NAME_WE)
set(QM ${QM_OUTPUT_DIR}/${TS_NAME_WE}.qm)
list(APPEND QM_FILES ${QM})
add_custom_command(
OUTPUT ${QM}
COMMAND ${LRELEASE_EXECUTABLE} ${TS} -qm ${QM}
DEPENDS ${TS}
COMMENT "Generating ${QM}"
)
endforeach()
add_custom_target(translations_qm ALL DEPENDS ${QM_FILES})
add_dependencies(translations_qm ${PROJECT_NAME})

View File

@ -0,0 +1,52 @@
# Variables for generating the version.
# Used in the application (config.h file and versioninfo.rc)
#
# Получаем полный временной штамп в UTC (пример: "2025-04-16 12:33:58 UTC")
string(TIMESTAMP BUILD_DATE "%Y-%m-%d %H:%M:%S UTC" UTC)
string(TIMESTAMP VERSION_DOY "%j" UTC) # день в году (001..366)
# Извлекаем компоненты даты и времени
string(SUBSTRING "${BUILD_DATE}" 0 4 YEAR_STR)
string(SUBSTRING "${BUILD_DATE}" 2 2 VERSION_YY)
string(SUBSTRING "${BUILD_DATE}" 5 2 VERSION_MM)
string(SUBSTRING "${BUILD_DATE}" 8 2 VERSION_DD)
string(SUBSTRING "${BUILD_DATE}" 11 2 VERSION_HH)
string(SUBSTRING "${BUILD_DATE}" 14 2 VERSION_MIN)
string(SUBSTRING "${BUILD_DATE}" 17 2 VERSION_SS)
# Убираем ведущие нули путём преобразования в числа
math(EXPR VERSION_YY_NOZERO "${VERSION_YY}")
math(EXPR VERSION_MM_NOZERO "${VERSION_MM}")
math(EXPR VERSION_DD_NOZERO "${VERSION_DD}")
math(EXPR VERSION_HH_NOZERO "${VERSION_HH}")
math(EXPR VERSION_MIN_NOZERO "${VERSION_MIN}")
math(EXPR VERSION_SS_NOZERO "${VERSION_SS}")
math(EXPR VERSION_DOY_NOZERO "${VERSION_DOY}")
if (VERSION_FULLDATE)
# Полная дата: YY.MM.DD.NNN
# Считаем количество минут с начала суток
math(EXPR VERSION_NNN
"${VERSION_HH_NOZERO} * 60 + ${VERSION_MIN_NOZERO}"
)
set(PROJECT_VERSION_MAJOR ${VERSION_YY_NOZERO})
set(PROJECT_VERSION_MINOR ${VERSION_MM_NOZERO})
set(PROJECT_VERSION_PATCH ${VERSION_DD_NOZERO})
set(BUILD_NUM ${VERSION_NNN})
else()
# Версия от MAJOR, MINOR + YY + день года
# MAJOR и MINOR должны быть заданы ранее через `project(... VERSION ...)`
set(PROJECT_VERSION_PATCH ${VERSION_YY_NOZERO})
set(BUILD_NUM ${VERSION_DOY_NOZERO})
endif()
set(ORIGINAL_FILE_NAME ${RUNTIME_OUTPUT_NAME})
message(STATUS "Project '${PROJECT_NAME}' version: ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}.${BUILD_NUM}")

View File

@ -0,0 +1,35 @@
1 TYPELIB "versioninfo.rc"
1 VERSIONINFO
FILEVERSION @PROJECT_VERSION_MAJOR@, @PROJECT_VERSION_MINOR@, @PROJECT_VERSION_PATCH@, @BUILD_NUM@
PRODUCTVERSION @PROJECT_VERSION_MAJOR@, @PROJECT_VERSION_MINOR@, @PROJECT_VERSION_PATCH@, @BUILD_NUM@
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "@SOFT_DEVELOPER@"
VALUE "FileDescription", "@PROJECT_DESCRIPTION@"
VALUE "FileVersion","@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.@BUILD_NUM@"
VALUE "InternalName", "@PROJECT_NAME@"
VALUE "LegalCopyright", "Copyright (c) @YEAR_STR@ @SOFT_DEVELOPER@"
VALUE "OriginalFilename", "@ORIGINAL_FILE_NAME@"
VALUE "ProductName", "@PROJECT_NAME@"
VALUE "ProductVersion","@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.@BUILD_NUM@"
VALUE "BuildDate", "@BUILD_DATE@"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END

View File

@ -0,0 +1,159 @@
/****************************************************************************
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#include "application_config.h"
#include "config.h"
#include <QtWidgets/QApplication>
#include <QtCore/QTranslator>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QStringList>
#include <QtGui/QScreen>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
# include <QtCore/QTextCodec>
#endif
//==============================================================================
void Application::initialize()
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
#endif
#if defined (PROG_NAME)
QApplication::setApplicationName( QString(PROG_NAME) );
#endif
#if defined (SOFT_DEVELOPER)
QApplication::setOrganizationName( QString(SOFT_DEVELOPER) );
#endif
#if defined (DEVELOPER_DOMAIN)
QApplication::setOrganizationDomain( QString(DEVELOPER_DOMAIN) );
#endif
#if defined (PROG_VERSION)
QApplication::setApplicationVersion( QString(PROG_VERSION) );
#endif
#if defined (BUILD_DATE)
qApp->setProperty( "buildDate", QString(BUILD_DATE) );
#endif
}
//==============================================================================
QString Application::applicationRootPath()
{
QString path { QApplication::applicationDirPath() };
if ( path.right(1) != "/" ) {
path += "/";
}
if (path.right(5) == "/bin/") {
path.remove( path.length() - 4, 4 );
}
return path;
}
//==============================================================================
void Application::installTranslations(const QString &lng)
{
const QString dirName { applicationRootPath() + "translations/" };
QDir translationsDir { dirName };
QStringList filesList = translationsDir.entryList(
QStringList() << QString("*_%1.qm").arg(lng),
QDir::Files
);
for (const QString &fileName: std::as_const(filesList)) {
QTranslator *translator = new QTranslator(QApplication::instance());
if (translator->load( dirName + fileName )) {
QApplication::instance()->installTranslator( translator );
}
else {
delete translator;
}
}
}
//==============================================================================
QWidget* mainWindow()
{
QWidgetList list = QApplication::topLevelWidgets();
for ( auto widget : std::as_const(list) ) {
if (widget && QString(widget->metaObject()->className()).contains("MainWindow"))
return widget;
}
return list.isEmpty() ? nullptr : list.first();
}
//==============================================================================
bool Application::moveToCenterMainWindow(QWidget *w)
{
if (!w) return false;
QRect targetRect;
QWidget *mainW = mainWindow();
if (mainW && mainW->isVisible()) {
targetRect = mainW->geometry();
}
else {
QScreen *screen = mainW ? mainW->screen() : nullptr;
if (mainW && !screen) {
QPoint pos = mainW->geometry().center();
screen = QGuiApplication::screenAt(pos);
}
if (screen) {
targetRect = screen->geometry();
}
}
if (targetRect.isValid()) {
QSize dialogSize = w->size();
QPoint centerPos = targetRect.center() - QPoint(dialogSize.width() / 2, dialogSize.height() / 2);
w->move(centerPos);
return true;
}
return false;
}
//==============================================================================

View File

@ -0,0 +1,47 @@
/****************************************************************************
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#pragma once
#ifndef APP_CONFIG_H
#define APP_CONFIG_H
#include <QtCore/QString>
#include <QtWidgets/QWidget>
//==============================================================================
class Application
{
Q_DISABLE_COPY(Application)
public:
static void initialize();
static QString applicationRootPath();
static void installTranslations(const QString &lng = "ru");
static bool moveToCenterMainWindow(QWidget *w);
private:
Application() = delete;
};
#endif // APP_CONFIG_H
//==============================================================================

View File

@ -0,0 +1,12 @@
<RCC>
<qresource prefix="/">
<file>icons/cancel-40.png</file>
<file>icons/change-theme-40.png</file>
<file>icons/close-40.png</file>
<file>icons/ok-40.png</file>
<file>icons/opened-folder-40.png</file>
<file>icons/restart-40.png</file>
<file>icons/save-as-40.png</file>
<file>icons/shutdown-40.png</file>
</qresource>
</RCC>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 487 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 534 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 840 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

BIN
_resources/main.ico 100644

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View File

@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/">
<file>images/main_icon.png</file>
<file>images/main_title.png</file>
</qresource>
</RCC>

View File

@ -0,0 +1 @@
IDI_ICON1 ICON "main.ico"

View File

@ -0,0 +1,82 @@
cmake_minimum_required(VERSION 4.0)
project(circular_menu_example
VERSION 1.0
DESCRIPTION "Example use Circular menu lib"
LANGUAGES CXX
)
include(${CMAKE_CURRENT_SOURCE_DIR}/../_cmake/app_settings.cmake)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS
Core Widgets
)
set(PROJECT_SOURCES
main.cpp
main_window.cpp
main_window.h
main_window.ui
${COMMON_SOURCES_DIR}/application_config.h
${COMMON_SOURCES_DIR}/application_config.cpp
)
set(PROJECT_RESOURCES
${RESOURCES_DIR}/main.qrc
${RESOURCES_DIR}/icons.qrc
)
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
set(PROJECT_RC_FILES
${RESOURCES_DIR}/main_icon.rc
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
)
endif()
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(${PROJECT_NAME}
MANUAL_FINALIZATION
${PROJECT_SOURCES}
${PROJECT_RESOURCES}
${PROJECT_RC_FILES}
)
else()
add_executable(${PROJECT_NAME}
${PROJECT_SOURCES}
${PROJECT_RESOURCES}
${PROJECT_RC_FILES}
)
endif()
target_link_directories(${PROJECT_NAME} PRIVATE
${DISTRIB_DIR}
)
include(${CMAKE_INC_DIR}/target_options.cmake)
target_link_libraries(${PROJECT_NAME} PRIVATE
Qt${QT_VERSION_MAJOR}::Core
Qt${QT_VERSION_MAJOR}::Widgets
_circular_menu
)
target_include_directories(${PROJECT_NAME} PRIVATE
${SYSTEM_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${COMMON_SOURCES_DIR}
${ROOT_PROJECT_DIR}lib_circular_menu
)
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
set_target_properties(${PROJECT_NAME} PROPERTIES
WIN32_EXECUTABLE TRUE
)
endif()
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(${PROJECT_NAME})
endif()
include(${CMAKE_INC_DIR}/post_build.cmake)

View File

@ -0,0 +1,22 @@
#include "main_window.h"
#include <QtWidgets/QApplication>
#include "application_config.h"
//==============================================================================
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Application::initialize();
Application::installTranslations();
// Создание главного окна:
MainWindow w;
w.show();
a.setQuitOnLastWindowClosed(true);
return a.exec();
}
//==============================================================================

View File

@ -0,0 +1,80 @@
/****************************************************************************
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#include "main_window.h"
#include "./ui_main_window.h"
#include <QtWidgets/QMessageBox>
#include "circular_menu.h"
//==============================================================================
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
initialize();
}
//==============================================================================
MainWindow::~MainWindow()
{
delete ui;
}
//==============================================================================
void MainWindow::initialize()
{
setWindowTitle( QApplication::applicationName() );
const QList<QAction*> actions = this->findChildren<QAction*>();
QList<QAction*> menuActions;
for (QAction* action: actions) {
if (!action || !action->objectName().contains("action"))
continue;
if (action != ui->actionExit)
connect(action, &QAction::triggered, this, &MainWindow::actionClick);
menuActions.append(action);
}
connect(ui->actionExit, &QAction::triggered, this, &MainWindow::close);
CircularMenu *circularMenu = new CircularMenu(this);
circularMenu->addActions(menuActions);
circularMenu->setHotKey(Qt::Key_Alt);
}
//==============================================================================
void MainWindow::actionClick()
{
QAction *action = qobject_cast<QAction*>(sender());
if (action) {
QMessageBox::information(this, tr("Информация"),
tr("Выбран пункт меню '%1'").arg(action->text()));
}
}
//==============================================================================

View File

@ -0,0 +1,58 @@
/****************************************************************************
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#pragma once
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtWidgets/QMainWindow>
//==============================================================================
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
//==============================================================================
// Главное окно
//==============================================================================
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
void initialize();
private slots:
void actionClick();
};
#endif // MAINWINDOW_H
//==============================================================================

View File

@ -0,0 +1,154 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>561</width>
<height>345</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<property name="windowIcon">
<iconset resource="../_resources/main.qrc">
<normaloff>:/images/main_icon.png</normaloff>:/images/main_icon.png</iconset>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Нажмите Alt чтобы вызвать круговое меню</string>
</property>
<property name="alignment">
<set>Qt::AlignmentFlag::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>561</width>
<height>21</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>Файл</string>
</property>
<addaction name="actionOpen"/>
<addaction name="actionSaveAs"/>
<addaction name="actionExit"/>
</widget>
<widget class="QMenu" name="menuEdit">
<property name="title">
<string>Правка</string>
</property>
<addaction name="actionUndo"/>
<addaction name="actionApply"/>
</widget>
<widget class="QMenu" name="menuView">
<property name="title">
<string>Вид</string>
</property>
<addaction name="actionChange"/>
</widget>
<addaction name="menuFile"/>
<addaction name="menuEdit"/>
<addaction name="menuView"/>
</widget>
<widget class="QToolBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<property name="iconSize">
<size>
<width>32</width>
<height>32</height>
</size>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionOpen"/>
<addaction name="actionSaveAs"/>
<addaction name="actionUndo"/>
<addaction name="actionApply"/>
<addaction name="actionChange"/>
</widget>
<action name="actionOpen">
<property name="icon">
<iconset resource="../_resources/icons.qrc">
<normaloff>:/icons/opened-folder-40.png</normaloff>:/icons/opened-folder-40.png</iconset>
</property>
<property name="text">
<string>Открыть...</string>
</property>
</action>
<action name="actionSaveAs">
<property name="icon">
<iconset resource="../_resources/icons.qrc">
<normaloff>:/icons/save-as-40.png</normaloff>:/icons/save-as-40.png</iconset>
</property>
<property name="text">
<string>Сохранить как...</string>
</property>
</action>
<action name="actionExit">
<property name="icon">
<iconset resource="../_resources/icons.qrc">
<normaloff>:/icons/shutdown-40.png</normaloff>:/icons/shutdown-40.png</iconset>
</property>
<property name="text">
<string>Выход</string>
</property>
</action>
<action name="actionUndo">
<property name="icon">
<iconset resource="../_resources/icons.qrc">
<normaloff>:/icons/restart-40.png</normaloff>:/icons/restart-40.png</iconset>
</property>
<property name="text">
<string>Отменить последнее действие</string>
</property>
</action>
<action name="actionChange">
<property name="icon">
<iconset resource="../_resources/icons.qrc">
<normaloff>:/icons/change-theme-40.png</normaloff>:/icons/change-theme-40.png</iconset>
</property>
<property name="text">
<string>Разделить</string>
</property>
</action>
<action name="actionApply">
<property name="icon">
<iconset resource="../_resources/icons.qrc">
<normaloff>:/icons/ok-40.png</normaloff>:/icons/ok-40.png</iconset>
</property>
<property name="text">
<string>Применить всё</string>
</property>
</action>
</widget>
<resources>
<include location="../_resources/main.qrc"/>
<include location="../_resources/icons.qrc"/>
</resources>
<connections/>
<buttongroups>
<buttongroup name="buttonGroup"/>
</buttongroups>
</ui>

View File

@ -0,0 +1,57 @@
cmake_minimum_required(VERSION 4.0)
project(_circular_menu
VERSION 1.0
DESCRIPTION "Circular menu library for Qt projects"
LANGUAGES CXX)
include(${CMAKE_CURRENT_SOURCE_DIR}/../_cmake/lib_settings.cmake)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS
Core Widgets
)
set(PUBLIC_LIBRARY_HEADERS
circular_menu.h
)
set(PROJECT_SOURCES
private/circular_menu.cpp
${COMMON_SOURCES_DIR}/application_config.h
${COMMON_SOURCES_DIR}/application_config.cpp
)
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
set(PROJECT_RC_FILES
${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc
)
endif()
add_library(${PROJECT_NAME} SHARED
${PUBLIC_LIBRARY_HEADERS}
${PROJECT_SOURCES}
${PROJECT_RC_FILES}
)
include(${CMAKE_INC_DIR}/target_options.cmake)
target_include_directories(${PROJECT_NAME} PRIVATE
${SYSTEM_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${COMMON_SOURCES_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/private
)
target_link_directories(${PROJECT_NAME} PRIVATE
${CMAKE_LIBRARY_OUTPUT_DIRECTORY}
)
target_link_libraries(${PROJECT_NAME} PRIVATE
Qt${QT_VERSION_MAJOR}::Core
Qt${QT_VERSION_MAJOR}::Widgets
)
target_compile_definitions(${PROJECT_NAME} PRIVATE
LIB_CIRCULAR_MENU
)

View File

@ -0,0 +1,80 @@
/****************************************************************************
** Copyright (c) 2025 Evgeny Teterin (nayk) <nayk@nxt.ru>
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#pragma once
#ifndef CIRCULAR_MENU_H
#define CIRCULAR_MENU_H
#if defined (LIB_CIRCULAR_MENU)
# define CIRCULAR_MENU_EXPORT Q_DECL_EXPORT
#else
# define CIRCULAR_MENU_EXPORT Q_DECL_IMPORT
#endif
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
#include <QtCore/QList>
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
# include <QtGui/QAction>
#else
# include <QtWidgets/QAction>
#endif
#include <QtCore/QEvent>
#include <QtGui/QPaintEvent>
#include <QtGui/QResizeEvent>
//==============================================================================
class CircularMenuData;
//==============================================================================
class CIRCULAR_MENU_EXPORT CircularMenu : public QWidget
{
Q_OBJECT
public:
explicit CircularMenu(QWidget *parent = nullptr);
virtual ~CircularMenu();
void addAction(QAction *action);
void addActions(QList<QAction*> actions);
qsizetype count() const;
QList<QAction*> actions() const;
QAction *actionAt(qsizetype index) const;
bool removeAction(qsizetype index, qsizetype count = 1);
void clear();
void setHotKey(Qt::Key key);
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private:
CircularMenuData *d;
};
//==============================================================================
#endif // CIRCULAR_MENU_H

View File

@ -0,0 +1,362 @@
#include "circular_menu.h"
#include <QtCore/QPointer>
#include <QtGui/QKeyEvent>
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
#include <QtGui/QIcon>
#include <cmath>
#include "application_config.h"
//==============================================================================
class CircularMenuData
{
public:
qsizetype activeIndex {-1};
int radius {210};
int buttonRadius {54};
int iconSize {40};
QList<QPointer<QAction>> actions;
QList<QPointer<QAction>> visibleActions;
Qt::Key key {Qt::Key_Alt};
//
CircularMenuData() = default;
virtual ~CircularMenuData() = default;
void updateVisibleActions()
{
visibleActions.clear();
for (auto i = 0; i < actions.size(); ++i) {
if (actions.at(i) && actions.at(i)->isVisible()
&& !actions.at(i)->isCheckable()) {
visibleActions.append(actions.at(i));
}
}
};
};
//==============================================================================
CircularMenu::CircularMenu(QWidget *parent)
: QWidget{parent}
, d{new CircularMenuData}
{
setWindowFlags(windowFlags()
| Qt::Dialog
| Qt::FramelessWindowHint
| Qt::WindowStaysOnTopHint
);
setAttribute(Qt::WA_TranslucentBackground);
setWindowModality(Qt::WindowModal);
setMouseTracking(true);
setFixedSize(40 + 2 * (d->radius + d->buttonRadius),
40 + 2 * (d->radius + d->buttonRadius));
if (parent) {
parent->installEventFilter(this);
}
this->installEventFilter(this);
}
//==============================================================================
CircularMenu::~CircularMenu()
{
delete d;
}
//==============================================================================
void CircularMenu::addAction(QAction *action)
{
if (action) {
d->actions.append( QPointer<QAction>(action) );
d->updateVisibleActions();
update();
}
}
//==============================================================================
void CircularMenu::addActions(QList<QAction *> actions)
{
for (auto action: actions) {
if (action) {
d->actions.append( QPointer<QAction>(action) );
}
}
d->updateVisibleActions();
update();
}
//==============================================================================
qsizetype CircularMenu::count() const
{
return d->actions.size();
}
//==============================================================================
QList<QAction*> CircularMenu::actions() const
{
QList<QAction*> actions;
for (auto i = 0; i < d->actions.size(); ++i) {
if (d->actions.at(i))
actions.append(d->actions.at(i).data());
}
return actions;
}
//==============================================================================
QAction *CircularMenu::actionAt(qsizetype index) const
{
if (index < 0)
return nullptr;
if (index >= d->actions.size())
return nullptr;
return
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
d->actions.at(index).data();
#else
d->actions.at(static_cast<int>(index)).data();
#endif
}
//==============================================================================
bool CircularMenu::removeAction(qsizetype index, qsizetype count)
{
if (index < 0)
return false;
if (index >= d->actions.size())
return false;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
d->actions.remove(index, count);
#else
d->actions.erase(d->actions.begin() + index,
d->actions.begin() + index + count);
#endif
d->updateVisibleActions();
update();
return true;
}
//==============================================================================
void CircularMenu::clear()
{
d->actions.clear();
d->updateVisibleActions();
}
//==============================================================================
void CircularMenu::setHotKey(Qt::Key key)
{
d->key = key;
}
//==============================================================================
bool CircularMenu::eventFilter(QObject *obj, QEvent *event)
{
if (!obj || !event)
return false;
if ((obj != parent()) && (obj != this))
return false;
if ((event->type() == QMouseEvent::MouseMove) && isVisible()) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (!mouseEvent)
return false;
const QPoint center = rect().center();
const QPoint mousePos = mouseEvent->pos();
qsizetype newActiveIndex = -1;
const auto count = d->visibleActions.size();
for (auto i = 0; i < count; ++i) {
if (!d->visibleActions.at(i) || !d->visibleActions.at(i)->isEnabled()) continue;
// Вычисляем позицию кнопки
double angle = 2.0 * M_PI * static_cast<double>(i) / static_cast<double>(count) - M_PI / 2.0;
QPoint buttonCenter(
static_cast<int>(center.x() + d->radius * cos(angle)),
static_cast<int>(center.y() + d->radius * sin(angle))
);
// Проверяем попадание курсора в круглую область кнопки
QPoint diff = mousePos - buttonCenter;
double distanceToButton = sqrt(diff.x()*diff.x() + diff.y()*diff.y());
if (distanceToButton <= (d->buttonRadius + 10)) {
newActiveIndex = i;
break; // Курсор может быть только над одной кнопкой
}
}
if ((newActiveIndex != d->activeIndex) && (newActiveIndex != -1)
&& (newActiveIndex < d->visibleActions.size())) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QAction *action = d->visibleActions.at(newActiveIndex);
#else
QAction *action = d->visibleActions.at(static_cast<int>(newActiveIndex));
#endif
if (action && action->isEnabled()) {
d->activeIndex = newActiveIndex;
update();
}
}
}
else if ((event->type() == QMouseEvent::MouseButtonPress) && isVisible()) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (!mouseEvent)
return false;
if (mouseEvent->button() == Qt::LeftButton
&& (d->activeIndex != -1) && (d->activeIndex < d->visibleActions.size())) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QAction *action = d->visibleActions.at(d->activeIndex);
#else
QAction *action = d->visibleActions.at(static_cast<int>(d->activeIndex));
#endif
this->hide();
if (action && action->isEnabled())
action->trigger();
return true;
}
}
else if ((event->type() == QKeyEvent::KeyRelease) && isVisible()) {
this->hide();
return false;
}
else if (event->type() == QKeyEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (!keyEvent)
return false;
if (keyEvent->key() != d->key) {
this->hide();
return false;
}
d->updateVisibleActions();
d->activeIndex = d->visibleActions.isEmpty() ? -1 : 0;
Application::moveToCenterMainWindow(this);
this->show();
return true;
}
return false;
}
//==============================================================================
void CircularMenu::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// Рисуем круглый фон
painter.setBrush(QBrush(QColor(0, 0, 0, 50)));
painter.setPen(QPen(QColor(255, 255, 255, 60), 4));
painter.drawEllipse(rect());
// Draw menu circle
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(0, 5, 10, 130));
painter.drawEllipse(rect().center(),
d->radius - d->buttonRadius / 2 - 30,
d->radius - d->buttonRadius / 2 - 30);
// Draw buttons
const auto count = d->visibleActions.size();
const QPoint center = rect().center();
for (auto i = 0; i < count; ++i) {
if (!d->visibleActions.at(i)) continue;
// Calculate button position
double angle = 2.0 * M_PI * static_cast<double>(i) / static_cast<double>(count) - M_PI / 2.0;
int x = static_cast<int>(center.x() + d->radius * cos(angle) - d->buttonRadius);
int y = static_cast<int>(center.y() + d->radius * sin(angle) - d->buttonRadius);
// Draw button
if (i == d->activeIndex) {
painter.setBrush(QColor(0, 15, 50, 200));
painter.setPen(QPen(QColor(0, 180, 255, 200), 5));
}
else {
painter.setBrush(QColor(0, 5, 10, 200));
painter.setPen(QPen(QColor(255, 255, 255, 180), 3));
}
painter.drawEllipse(QPoint(x + d->buttonRadius, y + d->buttonRadius),
d->buttonRadius, d->buttonRadius);
if (!d->visibleActions.at(i)->icon().isNull()) {
QRect iconRect(x + d->buttonRadius - d->iconSize / 2,
y + d->buttonRadius - d->iconSize / 2,
d->iconSize, d->iconSize);
if (d->visibleActions.at(i)->isEnabled()) {
d->visibleActions.at(i)->icon().paint(&painter, iconRect);
}
else {
painter.save();
painter.setOpacity(0.4); // Make icon semi-transparent
QIcon::Mode mode = QIcon::Disabled;
QIcon::State state = d->visibleActions.at(i)->isChecked() ? QIcon::On : QIcon::Off;
d->visibleActions.at(i)->icon().paint(&painter, iconRect, Qt::AlignCenter, mode, state);
painter.restore();
}
}
if (i == d->activeIndex) {
QRect r(0, 0, d->radius * 2 - 20, d->radius * 2 - 20);
r.moveCenter(rect().center());
QFont font {painter.font()};
font.setPointSize(14);
painter.setFont(font);
painter.setBrush(Qt::NoBrush);
painter.setPen(Qt::white);
painter.drawText(r,
Qt::AlignCenter,
d->visibleActions.at(i)->text());
}
}
}
//==============================================================================
void CircularMenu::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
QRegion region(rect(), QRegion::Ellipse);
setMask(region);
}
//==============================================================================