### KAboutLicense: Print license key enum values Source: https://context7.com/frameworks/kcoreaddons/llms.txt Provides examples of how to print the integer representation of predefined license key enum values. ```cpp #include // Print license key enum value qDebug() << (int)KAboutLicense::MIT; // 8 qDebug() << (int)KAboutLicense::Apache_V2; // 10 ``` -------------------------------- ### Finalize and Install QML Module Source: https://github.com/frameworks/kcoreaddons/blob/master/src/qml/CMakeLists.txt Completes the QML module configuration and specifies the installation directory and export target. This makes the module available for use after installation. ```cmake ecm_finalize_qml_module(kcoreaddonsplugin DESTINATION ${KDE_INSTALL_QMLDIR} EXPORT KF6CoreAddonsTargets) ``` -------------------------------- ### Define a Qt Plugin using kcoreaddons_add_plugin Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a Qt plugin, specifying its sources and installation namespace, and linking it with KCoreAddons. ```cmake kcoreaddons_add_plugin(qtplugin SOURCES qtplugin.cpp INSTALL_NAMESPACE "namespace") ecm_mark_as_test(qtplugin) target_link_libraries(qtplugin KF6::CoreAddons autotests_static) ``` -------------------------------- ### Install KDE MIME Types XML Source: https://github.com/frameworks/kcoreaddons/blob/master/src/mimetypes/CMakeLists.txt Installs the KDE MIME types XML file to the specified installation directory. This ensures applications can correctly identify file types. ```cmake install(FILES kde6.xml DESTINATION ${KDE_INSTALL_MIMEDIR}) ``` -------------------------------- ### Getting Highlight Ranges with KFuzzyMatcher Source: https://context7.com/frameworks/kcoreaddons/llms.txt Use `KFuzzyMatcher::matchedRanges` to obtain a list of `Range` objects indicating the start and length of matched substrings for highlighting. The `All` flag can be used to get ranges even for partial matches. ```cpp #include #include // Get match ranges for highlighting in a view QList ranges = KFuzzyMatcher::matchedRanges("hlo", "hello"); // [Range{0,1}, Range{3,2}] -> 'h' at 0, 'lo' at 3 for (auto &range : ranges) qDebug() << "start:" << range.start << "len:" << range.length; // Partial-match ranges (even if pattern doesn't fully match) auto allRanges = KFuzzyMatcher::matchedRanges("git", "gti", KFuzzyMatcher::RangeType::All); // [Range{0,1}, Range{2,1}] ``` -------------------------------- ### Using KAboutData and KFormat via PySide6 Python Bindings Source: https://context7.com/frameworks/kcoreaddons/llms.txt Demonstrates how to use `KAboutData` and `KAboutPerson` for application metadata and `KFormat` for string formatting within Python applications using PySide6. Ensure KCoreAddons Python package is installed. ```python #!/usr/bin/env python3 # Requires: pip install PySide6; KCoreAddons Python package installed import sys from PySide6 import QtCore from KCoreAddons import KAboutData, KAboutPerson, KFormat app = QtCore.QCoreApplication(sys.argv) # --- KAboutData --- about = KAboutData("myapp", "My Application", "1.0.0") about.setShortDescription("A sample application") author = KAboutPerson("Ada Lovelace", "Lead developer", "ada@example.org") about.addAuthor(author) KAboutData.setApplicationData(about) print(f"App: {about.displayName()} {about.version()}") print(f"Author: {about.authors()[0].name()}") print(f"QCoreApplication name: {QtCore.QCoreApplication.applicationName()}") # App: My Application 1.0.0 # Author: Ada Lovelace # QCoreApplication name: myapp ``` -------------------------------- ### Define a Static Plugin using kcoreaddons_add_plugin Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a static plugin, specifying its sources, installation namespace, and linking it with KCoreAddons and autotests_static. ```cmake kcoreaddons_add_plugin(static_jsonplugin_cmake_macro SOURCES statickpluginclass.cpp INSTALL_NAMESPACE "staticnamespace" STATIC) target_link_libraries(static_jsonplugin_cmake_macro KF6::CoreAddons autotests_static) ``` -------------------------------- ### Define a Dynamic Plugin using kcoreaddons_add_plugin Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a dynamic plugin, specifying its sources, installation namespace, and linking it with KCoreAddons and other necessary targets. ```cmake kcoreaddons_add_plugin(jsonplugin_cmake_macro SOURCES kpluginclass.cpp INSTALL_NAMESPACE "namespace") ecm_mark_as_test(jsonplugin_cmake_macro) target_link_libraries(jsonplugin_cmake_macro KF6::CoreAddons autotests_static plugin_classes) target_link_libraries(plugin_classes Qt6::Core) ``` -------------------------------- ### Define a Widgets Plugin Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a plugin specifically for widgets, specifying its sources, installation namespace, and linking it with KCoreAddons and Qt6::Widgets. ```cmake kcoreaddons_add_plugin(widgetsplugin SOURCES widgetsplugin.cpp INSTALL_NAMESPACE "widgets") ecm_mark_as_test(widgetsplugin) target_link_libraries(widgetsplugin KF6::CoreAddons Qt6::Widgets) ``` -------------------------------- ### Define Another Static Plugin Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines an additional static plugin, specifying its sources, installation namespace, and linking it with KCoreAddons and autotests_static. ```cmake kcoreaddons_add_plugin(static_jsonplugin_cmake_macro_2 SOURCES statickpluginclass_2.cpp INSTALL_NAMESPACE "staticnamespace2" STATIC) target_link_libraries(static_jsonplugin_cmake_macro_2 KF6::CoreAddons autotests_static) ``` -------------------------------- ### Initialize KAboutData for an Application Source: https://context7.com/frameworks/kcoreaddons/llms.txt Sets up application metadata including name, version, authors, and license. It also enables automatic command-line options like --version and --author. ```cpp #include #include #include int main(int argc, char *argv[]) { QCoreApplication app(argc, argc); KAboutData about( QStringLiteral("myapp"), // component name (internal) QStringLiteral("My Application"), // display name (translatable) QStringLiteral("2.0.1"), // version QStringLiteral("A sample KDE application"), KAboutLicense::LGPL_V2_1, QStringLiteral("Copyright (C) 2024 Jane Developer"), QString(), // optional free-form text QStringLiteral("https://myapp.example.org"), QStringLiteral("bugs@myapp.example.org") ); about.setOrganizationDomain("example.org"); about.setDesktopFileName("org.example.myapp"); about.addAuthor( QStringLiteral("Jane Developer"), QStringLiteral("Lead developer"), QStringLiteral("jane@example.org"), QStringLiteral("https://jane.example.org") ); about.addCredit( QStringLiteral("John Tester"), QStringLiteral("Testing") ); about.addComponent( QStringLiteral("SomeLib"), QStringLiteral("Does awesome stuff"), QStringLiteral("3.1"), QStringLiteral("https://somelib.example.com"), KAboutLicense::MIT ); // Propagates info to QCoreApplication and enables --version / --author flags KAboutData::setApplicationData(about); QCommandLineParser parser; about.setupCommandLine(&parser); parser.process(app); about.processCommandLine(&parser); qDebug() << "App:" << about.displayName() << about.version(); qDebug() << "Authors:" << about.authors().size(); qDebug() << "License SPDX:" << about.licenses().first().spdx(); // Output: // App: "My Application" "2.0.1" // Authors: 1 // License SPDX: "LGPL-2.1-only" return app.exec(); } ``` -------------------------------- ### KAboutLicense: Look up and use licenses by keyword Source: https://context7.com/frameworks/kcoreaddons/llms.txt Demonstrates how to find licenses using keywords like SPDX identifiers and access their properties. Use this for retrieving standard license information. ```cpp #include // Look up a license by SPDX keyword (case-insensitive, whitespace-stripped) KAboutLicense lic = KAboutLicense::byKeyword(QStringLiteral("GPL-2.0-or-later")); qDebug() << lic.name(); // "GPL v2 or later" qDebug() << lic.name(KAboutLicense::FullName); // "GNU General Public License Version 2 (or later)" qDebug() << lic.spdx(); // "GPL-2.0-or-later" qDebug() << lic.key(); // KAboutLicense::GPL_V2 ``` -------------------------------- ### KAboutLicense: Set predefined license with version restriction Source: https://context7.com/frameworks/kcoreaddons/llms.txt Shows how to set a predefined license (e.g., LGPL) for an application, specifying version constraints like 'or later versions'. ```cpp #include // Predefined license with version restriction KAboutData about("foo", "Foo", "1.0"); about.setLicense(KAboutLicense::LGPL_V2_1, KAboutLicense::OrLaterVersions); ``` -------------------------------- ### KAboutLicense: Add custom license text and from file Source: https://context7.com/frameworks/kcoreaddons/llms.txt Illustrates adding custom license text directly or loading it from a file. Useful for licenses not covered by predefined options. ```cpp #include // Custom inline license text about.addLicenseText( QStringLiteral("This software is provided 'as-is', without any warranty.") ); // License loaded from a file about.addLicenseTextFile(QStringLiteral("/path/to/LICENSE.txt")); ``` -------------------------------- ### Define a Plugin Without Metadata Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a plugin that does not require explicit metadata, specifying its sources and installation namespace. ```cmake kcoreaddons_add_plugin(pluginwithoutmetadata SOURCES pluginwithoutmetadata.cpp INSTALL_NAMESPACE "namespace") ecm_mark_as_test(pluginwithoutmetadata) target_link_libraries(pluginwithoutmetadata KF6::CoreAddons autotests_static) ``` -------------------------------- ### KFormat: Format byte sizes with different dialects Source: https://context7.com/frameworks/kcoreaddons/llms.txt Demonstrates formatting byte sizes using different binary unit dialects (IEC, Metric, JEDEC) and specifying precision. ```cpp #include #include #include KFormat fmt; // uses system locale by default // --- Byte sizes --- qDebug() << fmt.formatByteSize(1024); // IEC (default): "1.0 KiB" qDebug() << fmt.formatByteSize(1500000, 2, KFormat::MetricBinaryDialect); // "1.50 MB" qDebug() << fmt.formatByteSize(1024, 1, KFormat::JEDECBinaryDialect, KFormat::UnitKiloByte); // "1.0 KB" ``` -------------------------------- ### Add Executable and Link Libraries Source: https://github.com/frameworks/kcoreaddons/blob/master/tests/CMakeLists.txt These snippets show how to add executables and link them against Qt6::Widgets and KF6::CoreAddons. This is common for building GUI applications or tools that use KCoreAddons. ```cmake add_executable(kdirwatchtest_gui kdirwatchtest_gui.cpp) target_link_libraries(kdirwatchtest_gui Qt6::Widgets KF6::CoreAddons) ``` ```cmake add_executable(faceicontest faceicontest.cpp) target_link_libraries(faceicontest Qt6::Widgets KF6::CoreAddons) ``` ```cmake add_executable(texttohtmltest ktexttohtmltest.cpp) target_link_libraries(texttohtmltest Qt6::Widgets KF6::CoreAddons) ``` -------------------------------- ### Define a Static Plugin Without Metadata Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a static plugin that does not require explicit metadata, specifying its sources and installation namespace. ```cmake kcoreaddons_add_plugin(static_plugin_without_metadata SOURCES staticpluginwithoutmetadata.cpp INSTALL_NAMESPACE "staticnamespace3" STATIC) target_link_libraries(static_plugin_without_metadata KF6::CoreAddons autotests_static) ``` -------------------------------- ### Monitor Filesystem Changes with KDirWatch Source: https://context7.com/frameworks/kcoreaddons/llms.txt Sets up a KDirWatch instance to monitor directories and files for creation, deletion, and modification events. Connects signals to handle these events and demonstrates methods for adding, checking, stopping, restarting, and removing watched paths. ```cpp #include #include // Create a watcher and monitor several paths KDirWatch *watcher = new KDirWatch(qApp); // Watch a directory for file-level changes watcher->addDir(QStringLiteral("/home/user/docs"), KDirWatch::WatchFiles | KDirWatch::WatchSubDirs); // Watch a single file watcher->addFile(QStringLiteral("/etc/hostname")); // Connect signals QObject::connect(watcher, &KDirWatch::dirty, [](const QString &path) { qDebug() << "Modified:" << path; }); QObject::connect(watcher, &KDirWatch::created, [](const QString &path) { qDebug() << "Created:" << path; }); QObject::connect(watcher, &KDirWatch::deleted, [](const QString &path) { qDebug() << "Deleted:" << path; }); // Temporarily stop watching (no signals during this period) watcher->stopDirScan(QStringLiteral("/home/user/docs")); // ... do batch writes ... watcher->restartDirScan(QStringLiteral("/home/user/docs")); // Check if a path is watched if (watcher->contains(QStringLiteral("/etc/hostname"))) { qDebug() << "Watching /etc/hostname"; } // Remove a watch watcher->removeFile(QStringLiteral("/etc/hostname")); ``` -------------------------------- ### Simple Macro Expansion with KMacroExpander Source: https://context7.com/frameworks/kcoreaddons/llms.txt Use `KMacroExpander::expandMacros` with a `QHash` for simple string substitution. Macros are prefixed with '%' and can be enclosed in parentheses for multi-character keys. ```cpp #include #include #include // Simple QHash-based substitution: %var or %(var) QHash vars; vars["NAME"] = "World"; vars["VERSION"] = "6.27.0"; QString tmpl = "Hello, %(NAME)! KCoreAddons version: %VERSION"; KMacroExpander::expandMacros(tmpl, vars); qDebug() << tmpl; // "Hello, World! KCoreAddons version: 6.27.0" ``` -------------------------------- ### Implement Custom KJob for Asynchronous Operations Source: https://context7.com/frameworks/kcoreaddons/llms.txt Subclass KJob to perform non-blocking operations. Implement start() to begin work and use emitResult() to signal completion. Jobs self-delete by default after finishing. ```cpp #include #include #include // --- Implementing a custom job --- class MyDownloadJob : public KJob { Q_OBJECT public: explicit MyDownloadJob(const QUrl &url, QObject *parent = nullptr) : KJob(parent), m_url(url) { setCapabilities(KJob::Killable); } void start() override { startElapsedTimer(); // enables elapsedTime() QTimer::singleShot(0, this, &MyDownloadJob::doWork); } private Q_SLOTS: void doWork() { // simulate progress setTotalAmount(KJob::Bytes, 1000); setProcessedAmount(KJob::Bytes, 500); // on error: // setError(KJob::UserDefinedError + 1); // setErrorText(m_url.toString()); emitResult(); // emits result() and schedules deletion } protected: bool doKill() override { /* cancel network request */ return true; } QString errorString() const override { if (error() == KJob::UserDefinedError + 1) return tr("Failed to download %1").arg(errorText()); return KJob::errorString(); } private: QUrl m_url; }; // --- Using a job asynchronously --- void startJob() { auto *job = new MyDownloadJob(QUrl("https://example.com/file"), qApp); QObject::connect(job, &KJob::result, [](KJob *j) { if (j->error()) { qWarning() << "Error:" << j->errorString(); } else { qDebug() << "Done! Took" << j->elapsedTime() << "ms"; } }); QObject::connect(job, &KJob::percentChanged, [](KJob *, unsigned long pct) { qDebug() << "Progress:" << pct << "%"; }); job->start(); } // --- Synchronous execution (avoid when possible) --- void runSync() { auto *job = new MyDownloadJob(QUrl("https://example.com/file")); job->setAutoDelete(false); if (!job->exec()) { qWarning() << "Failed:" << job->errorString(); } delete job; } ``` -------------------------------- ### Load and Instantiate Plugin with KPluginFactory Source: https://context7.com/frameworks/kcoreaddons/llms.txt Use KPluginFactory to load a plugin and instantiate its main interface. Handles potential loading errors and provides access to plugin functionality. ```cpp #include #include "myplugininterface.h" class MyPlugin : public MyPluginInterface { public: MyPlugin(QObject *parent, const KPluginMetaData &meta, const QVariantList &) : MyPluginInterface(parent) { Q_UNUSED(meta) } void doWork() override { /* ... */ } }; K_PLUGIN_CLASS_WITH_JSON(MyPlugin, "myplugin.json") #include ``` ```cpp #include #include #include "myplugininterface.h" void loadPlugin() { KPluginMetaData meta(QStringLiteral("myplugin")); // Load factory and instantiate in one step auto result = KPluginFactory::instantiatePlugin(meta, qApp); if (result) { result.plugin->doWork(); } else { qWarning() << "Plugin load failed:" << result.errorString; // result.errorReason is a KPluginFactory::ResultErrorReason enum value } // Or load the factory first, then create multiple instances auto factoryResult = KPluginFactory::loadFactory(meta); if (factoryResult) { MyPluginInterface *obj = factoryResult.plugin->create(qApp); if (obj) obj->doWork(); } } ``` -------------------------------- ### Define a Static Plugin with a Specific Target Name Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This macro defines a static plugin with a target name that includes a specific identifier, specifying its sources, installation namespace, and linking it with KCoreAddons and autotests_static. ```cmake kcoreaddons_add_plugin(org.kde.test-staticplugin SOURCES statickpluginclass_3.cpp INSTALL_NAMESPACE "rdnstatic" STATIC) target_link_libraries(org.kde.test-staticplugin KF6::CoreAddons autotests_static) ``` -------------------------------- ### KJob - Asynchronous Job Base Class Source: https://context7.com/frameworks/kcoreaddons/llms.txt KJob is the base class for asynchronous operations. Subclasses implement start() for non-blocking work, with results delivered via the result() signal. exec() offers optional synchronous execution. Jobs self-delete by default after completion. ```APIDOC ## KJob - Asynchronous Job Base Class `KJob` is the base class for all asynchronous operations in KDE Frameworks. Subclasses implement `start()` to trigger work non-blocking; results are delivered through the `result()` signal. `exec()` provides optional synchronous execution. Jobs self-delete with `deleteLater()` after finishing by default. ### Implementing a custom job ```cpp #include #include #include class MyDownloadJob : public KJob { Q_OBJECT public: explicit MyDownloadJob(const QUrl &url, QObject *parent = nullptr) : KJob(parent), m_url(url) { setCapabilities(KJob::Killable); } void start() override { startElapsedTimer(); // enables elapsedTime() QTimer::singleShot(0, this, &MyDownloadJob::doWork); } private Q_SLOTS: void doWork() { // simulate progress setTotalAmount(KJob::Bytes, 1000); setProcessedAmount(KJob::Bytes, 500); // on error: // setError(KJob::UserDefinedError + 1); // setErrorText(m_url.toString()); emitResult(); // emits result() and schedules deletion } protected: bool doKill() override { /* cancel network request */ return true; } QString errorString() const override { if (error() == KJob::UserDefinedError + 1) return tr("Failed to download %1").arg(errorText()); return KJob::errorString(); } private: QUrl m_url; }; ``` ### Using a job asynchronously ```cpp void startJob() { auto *job = new MyDownloadJob(QUrl("https://example.com/file"), qApp); QObject::connect(job, &KJob::result, [](KJob *j) { if (j->error()) { qWarning() << "Error:" << j->errorString(); } else { qDebug() << "Done! Took" << j->elapsedTime() << "ms"; } }); QObject::connect(job, &KJob::percentChanged, [](KJob *, unsigned long pct) { qDebug() << "Progress:" << pct << "%"; }); job->start(); } ``` ### Synchronous execution (avoid when possible) ```cpp void runSync() { auto *job = new MyDownloadJob(QUrl("https://example.com/file")); job->setAutoDelete(false); if (!job->exec()) { qWarning() << "Failed:" << job->errorString(); } delete job; } ``` ``` -------------------------------- ### KPluginFactory - Loading and Instantiating Plugins Source: https://context7.com/frameworks/kcoreaddons/llms.txt KPluginFactory offers a type-safe way to create objects from Qt plugin shared libraries. The K_PLUGIN_CLASS_WITH_JSON macro is used on the plugin side to declare the factory, and KPluginFactory::instantiatePlugin() is used in the host application to load and create the plugin object. ```APIDOC ## KPluginFactory::instantiatePlugin() ### Description Loads a plugin factory and instantiates a plugin object of type T. ### Method `static Result instantiatePlugin(const KPluginMetaData &meta, QObject *parent = nullptr)` ### Parameters #### Path Parameters - **meta** (KPluginMetaData) - Required - Metadata for the plugin to load. - **parent** (QObject *) - Optional - Parent object for the created plugin instance. ### Response #### Success Response - **plugin** (T *) - A pointer to the instantiated plugin object. - **errorString** (QString) - A string describing any error that occurred. #### Response Example ```cpp auto result = KPluginFactory::instantiatePlugin(meta, qApp); if (result) { result.plugin->doWork(); } else { qWarning() << "Plugin load failed:" << result.errorString; } ``` ## KPluginFactory::loadFactory() ### Description Loads a plugin factory from the specified metadata. ### Method `static Result loadFactory(const KPluginMetaData &meta)` ### Parameters #### Path Parameters - **meta** (KPluginMetaData) - Required - Metadata for the plugin factory to load. ### Response #### Success Response - **plugin** (PluginFactory) - The loaded plugin factory. - **errorString** (QString) - A string describing any error that occurred. #### Response Example ```cpp auto factoryResult = KPluginFactory::loadFactory(meta); if (factoryResult) { MyPluginInterface *obj = factoryResult.plugin->create(qApp); if (obj) obj->doWork(); } ``` ``` -------------------------------- ### KFormat: Format generic value with units Source: https://context7.com/frameworks/kcoreaddons/llms.txt Demonstrates formatting a generic numerical value with associated units, allowing auto-adjustment of prefixes and specifying the dialect. ```cpp #include #include #include KFormat fmt; // uses system locale by default // --- Generic value with units --- qDebug() << fmt.formatValue(12300000.0, QStringLiteral("bit/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::MetricBinaryDialect); // "12.3 Mbit/s" ``` -------------------------------- ### Generate QML Module Documentation Source: https://github.com/frameworks/kcoreaddons/blob/master/src/qml/CMakeLists.txt Generates documentation for the QML module using a specified configuration file. This is typically used for API documentation generation. ```cmake ecm_generate_qdoc(kcoreaddonsplugin kcoreaddonsqml.qdocconf) ``` -------------------------------- ### Read Plugin Metadata with KPluginMetaData Source: https://context7.com/frameworks/kcoreaddons/llms.txt Loads and accesses metadata from Qt plugins or standalone JSON files using KPluginMetaData. It demonstrates how to retrieve standard fields like plugin ID, name, description, version, license, icon, and custom JSON data. ```cpp #include #include // Load metadata from an installed plugin file KPluginMetaData meta(QStringLiteral("kf6/kfileitemaction/myaction")); if (meta.isValid()) { qDebug() << "Plugin ID:" << meta.pluginId(); qDebug() << "Name:" << meta.name(); qDebug() << "Description:" << meta.description(); qDebug() << "Version:" << meta.version(); qDebug() << "License:" << meta.license(); qDebug() << "Icon:" << meta.iconName(); qDebug() << "Enabled by default:" << meta.isEnabledByDefault(); qDebug() << "MIME types:" << meta.mimeTypes(); qDebug() << "Authors:"; for (const KAboutPerson &p : meta.authors()) { qDebug() << " " << p.name() << p.emailAddress(); } // Access custom/extra JSON fields directly QJsonValue extra = meta.rawData().value("X-MyApp-CustomKey"); } // Find all plugins of a specific service type const QList plugins = KPluginMetaData::findPlugins(QStringLiteral("kf6/kfileitemaction")); for (const KPluginMetaData &p : plugins) { qDebug() << p.pluginId() << p.name(); } ``` -------------------------------- ### Specify Source Files for QML Module Source: https://github.com/frameworks/kcoreaddons/blob/master/src/qml/CMakeLists.txt Lists the source and header files associated with the QML module target. Ensure all necessary implementation and interface files are included. ```cmake target_sources(kcoreaddonsplugin PRIVATE formats.cpp formats.h kcoreaddonsplugin.cpp kuserproxy.cpp kuserproxy.h kosreleaseproxy.cpp types.h ) ``` -------------------------------- ### Simple and Scored Fuzzy String Matching with KFuzzyMatcher Source: https://context7.com/frameworks/kcoreaddons/llms.txt Use `matchSimple` for a quick boolean check or `match` for a scored comparison. Both require the pattern and the string to match against. ```cpp #include #include #include // Simple boolean match (no scoring overhead) bool ok = KFuzzyMatcher::matchSimple("kca", "KCoreAddons"); // true bool no = KFuzzyMatcher::matchSimple("gti", "git"); // false (sequential) // Scored match KFuzzyMatcher::Result r = KFuzzyMatcher::match("kca", "KCoreAddons"); qDebug() << r.matched << r.score; // true, ``` -------------------------------- ### KFormat: Format durations in various styles Source: https://context7.com/frameworks/kcoreaddons/llms.txt Shows different ways to format time durations, including standard H:M:S, abbreviated, with milliseconds, and spellout/decimal representations. ```cpp #include #include #include KFormat fmt; // uses system locale by default // --- Durations --- qDebug() << fmt.formatDuration(3723000); // "1:02:03" qDebug() << fmt.formatDuration(3723000, KFormat::InitialDuration); // "1h2m3s" qDebug() << fmt.formatDuration(3723000, KFormat::HideSeconds); // "1:02" qDebug() << fmt.formatDuration(5500, KFormat::ShowMilliseconds); // "0:05.500" qDebug() << fmt.formatDuration(3600000, KFormat::AbbreviatedDuration); // "1 hr" (since 6.11) qDebug() << fmt.formatSpelloutDuration(90060000); // "1 day and 1 hour" qDebug() << fmt.formatDecimalDuration(62500); // "1.04 minutes" ``` -------------------------------- ### KFormat: Format distance Source: https://context7.com/frameworks/kcoreaddons/llms.txt Shows how to format distance values, adapting to metric or imperial locales and specifying metric units explicitly. ```cpp #include #include #include KFormat fmt; // uses system locale by default // --- Distance (since 6.11) --- qDebug() << fmt.formatDistance(350.0); // "350 m" (metric locale) // "1,148 ft" (imperial locale) qDebug() << fmt.formatDistance(1500.0, KFormat::MetricDistanceUnits); // "1.5 km" ``` -------------------------------- ### Add a MODULE Library for a Qt Plugin Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This snippet adds a MODULE library, typically used for Qt plugins, specifying its source file and linking it with KCoreAddons. ```cmake add_library(org.kde.test MODULE qtplugin.cpp) target_link_libraries(org.kde.test KF6::CoreAddons) ``` -------------------------------- ### Password Obfuscation with KStringHandler Source: https://context7.com/frameworks/kcoreaddons/llms.txt Provides a simple, reversible obfuscation method for strings, suitable for non-sensitive data like configuration file passwords. Not intended for cryptographic security. ```cpp #include #include // Simple reversible obfuscation (for config-file passwords, NOT cryptographically secure) QString obf = KStringHandler::obscure("mypassword"); QString recovered = KStringHandler::obscure(obf); // == "mypassword" ``` -------------------------------- ### Shuffling Containers with KRandom Source: https://context7.com/frameworks/kcoreaddons/llms.txt Employ `KRandom::shuffle` to randomize the order of elements within a `QList` using the Fisher-Yates algorithm. You can use the global random generator or provide a custom `QRandomGenerator` for reproducible results. ```cpp #include #include #include // Shuffle a QList using the global random generator QList numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; KRandom::shuffle(numbers); qDebug() << numbers; // e.g. {7, 2, 9, 1, 5, 3, 10, 4, 6, 8} // Shuffle with a custom/seeded QRandomGenerator for reproducibility QRandomGenerator rng(42); QList words = {"apple", "banana", "cherry", "date"}; KRandom::shuffle(words, &rng); qDebug() << words; // deterministic order based on seed 42 ``` -------------------------------- ### Find Qt6 and Check Widgets Component Source: https://github.com/frameworks/kcoreaddons/blob/master/autotests/plugin/CMakeLists.txt This snippet finds the Qt6 package and checks if the Widgets component is available. If not, it returns early. ```cmake find_package(Qt6 ${REQUIRED_QT_VERSION} CONFIG QUIET OPTIONAL_COMPONENTS Widgets) if (NOT TARGET Qt6::Widgets) return() endif() ``` -------------------------------- ### Ranking Strings by Fuzzy Score using KFuzzyMatcher Source: https://context7.com/frameworks/kcoreaddons/llms.txt Iterate through candidates, score them using `KFuzzyMatcher::match`, and sort the results by score in descending order. Only matched strings are added to the scored list. ```cpp #include #include #include // Rank a list of strings by fuzzy score QStringList candidates = {"KFormat", "KJob", "KCoreAddons", "KDirWatch", "KConfig"}; const QString pattern = "kco"; using Pair = QPair; QList scored; for (const QString &s : candidates) { auto res = KFuzzyMatcher::match(pattern, s); if (res.matched) scored.append({res.score, s}); } std::sort(scored.begin(), scored.end(), [](const Pair &a, const Pair &b){ return a.first > b.first; // highest score first }); for (auto &[score, name] : scored) qDebug() << score << name; // Likely: KCoreAddons (highest), KConfig, ... ```