qt-coding-guide
Skill1 starsChanged 17 days agoMITView on GitHub
Modern Qt 6 and QML coding guide and MSBuild Windows tooling reference. Must be loaded whenever Qt/QML code is being created, edited, refactored, or reviewed, or when Qt C++ projects are being built with MSBuild on Windows.
In this repository6 other files it gives its agents.
- AGENTS.mdAGENTS.md
- askSkill
- easy-profiler-guideSkill
- github-deploy-winSkill
- githubSkill
- init-project-docsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
15 rules. About 0 are common, 2 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 29
Always place relevant pragmas before imports:
- Very specific: line 35
Ban
property varfor concrete types: Always declare explicit types (property string, property int, property Item, property MyCustomType). - Very specific: line 41
Lookup by explicit
id: Avoid climbing the visual tree via parent.parent. - Very specific: line 42
Use
required property: When components need data from external parents or loaders, require them explicitly rather than relying on dynamic … - Very specific: line 85
Every Q_PROPERTY setter must check for value changes before updating state and emitting change signals:
- Very specific: line 96
Explicit QObject Ownership: When returning a QObject* to QML from C++, ensure it has a C++ parent (new MyController(this)) or call …
- Very specific: line 98
Thread Safety: Never touch GUI/QML objects from worker threads.
- Very specific: line 106
Top-level / Window Views: Use QtQuick.Layouts (RowLayout, ColumnLayout, GridLayout) with Layout.fillWidth: true and Layout.preferredWidth …
- Very specific: line 107
Virtualized Views (
ListView,TableView): Avoid heavy QtQuick.Layouts inside delegates due to overhead during scrolling. - Very specific: line 108
Never anchor immediate children of a Layout: Do not set anchors or bind x/y/width/height directly on layout children.
- Very specific: line 114
Eliminate Superfluous Visual Nodes: Use a plain Item instead of Rectangle for non-rendering containers, wrappers, or spacers to avoid …
- Distinctive: line 134
Signal Handlers in Qt 6: Use arrow function syntax with explicit parameter names:
- Very specific: line 160
Import QtQml.targets as the last item in your .vcxproj:
- Very specific: line 171
Default: QmlAotEnabled=false in Debug (fast incremental developer workflow) and true in Release (~3.6x cold-cache startup speedup).
- Very specific: line 181
Build the
.sln: Always build the solution or pass /p:SolutionDir=<dir>\ to prevent sibling project include paths from breaking.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Qt 6 & QML Modern Coding Guide (Windows & MSBuild)
A distilled, comprehensive guide for developing modern, high-performance Qt 6 and QML desktop applications on Windows using Visual Studio and native MSBuild (.vcxproj).
When to Load This Skill
[!IMPORTANT] Load this skill whenever:
- Writing, editing, refactoring, or reviewing Qt 6 C++ or QML code.
- Integrating C++ backend models, services, or value types with QML.
- Building, configuring, or troubleshooting Qt projects using Visual Studio / MSBuild (
.vcxproj) on Windows.- Wiring or diagnosing Qt tooling (
qmllint,qmlcachegen,qmltyperegistrar,moc,windeployqt).
1. Core Architectural Principles
Strict MVVM & Separation of Concerns
- QML is strictly presentation: Visual layout, animations, states, and user interaction capture only.
- C++ owns all business logic: Algorithms, data validation, domain state, file I/O, networking, and worker threads belong in C++ classes.
- No business logic in JavaScript: Inline JavaScript in QML cannot be unit-tested with C++ harnesses (
QTest/GoogleTest), slows the V4 engine, breaks type analysis, and degrades maintainability.
Qt 6 Pragmas (Mandatory at Top of Documents)
Always place relevant pragmas before imports:
pragma ComponentBehavior: Bound: Strongly binds components (e.g. delegate scopes inListView), preventing expensive upward lookups and enabling static compilation.pragma ValueTypeBehavior: Addressable: Enables direct, in-place mutation of structured value type properties.pragma Singleton: Declares a QML singleton (pair with asingleton <Type> <Type>.qmlentry inqmldir; never double-register in C++).
Strict Typing & Static Safety
- Ban
property varfor concrete types: Always declare explicit types (property string,property int,property Item,property MyCustomType). Reservevarstrictly for truly polymorphic payloads. - Type-annotate JavaScript functions:
// ✅ Fast, fully compiled to bytecode/native C++ function calculateArea(rect: Item): real { return rect.width * rect.height; } - Lookup by explicit
id: Avoid climbing the visual tree viaparent.parent. Use explicit IDs to resolve bindings at compile time. - Use
required property: When components need data from external parents or loaders, require them explicitly rather than relying on dynamic scope lookups.
Lightweight Value Types (Q_GADGET / QML_VALUE_TYPE)
For data transfer objects (DTOs), records, and settings structs, avoid heap-allocated QObject instances. Declare stack-allocated structs with Q_GADGET:
struct ItemRecord {
Q_GADGET
QML_VALUE_TYPE(itemRecord)
Q_PROPERTY(int width MEMBER width)
Q_PROPERTY(int height MEMBER height)
Q_PROPERTY(double durationSec MEMBER durationSec)
public:
int width = 0;
int height = 0;
double durationSec = 0.0;
};2. Modern C++ & QML Integration
Dependency Injection over Context Properties
- Never use
rootContext()->setContextProperty()in Qt 6: It breaks compile-time type verification, confusesqmllint, and impairs tool refactoring. - Inject via
setInitialProperties():
In QML:QQmlApplicationEngine engine; engine.setInitialProperties({ { "backendController", QVariant::fromValue(&myController) } }); engine.loadFromModule("MyProject.Module", "Main");required property MyController backendController
Header Registration Macros
Register C++ types in headers using native macros (requires #include <QtQmlIntegration>):
QML_ELEMENT: Standard instantiable QML item.QML_SINGLETON: Shared global manager.QML_UNCREATABLE: For enums or abstract interfaces.QML_NAMED_ELEMENT(Name): Custom QML type name.QML_VALUE_TYPE(name): ForQ_GADGETvalue structs.
Mandatory Setter Equality Guards
Every Q_PROPERTY setter must check for value changes before updating state and emitting change signals:
void setStatus(const QString& status) {
if (_status == status) return;
_status = status;
emit statusChanged();
}Missing guards cause cascading event loops, high CPU utilization, and infinite binding loops.
Memory Management & Thread Safety
- Explicit QObject Ownership: When returning a
QObject*to QML from C++, ensure it has a C++ parent (new MyController(this)) or callQQmlEngine::setObjectOwnership(obj, QQmlEngine::CppOwnership). Unparented objects are collected by QML garbage collection, producing dangling pointers and crashes. - Lifecycle Protection with
QPointer<T>: Store C++ references to QML-instantiated objects inQPointer<T>to automatically null pointers if QML destroys the item. - Thread Safety: Never touch GUI/QML objects from worker threads. Communicate across threads exclusively via Qt signals/slots (
Qt::QueuedConnection) orQMetaObject::invokeMethod(). - Model Exposure: Inherit from
QAbstractListModelwith granular notifications (beginInsertRows()/endInsertRows(),dataChanged()). Never pass rawQList<QObject*>or untypedQVariantListfor collections.
3. Layouts & Visual Performance
Proper Layout Strategy
- Top-level / Window Views: Use
QtQuick.Layouts(RowLayout,ColumnLayout,GridLayout) withLayout.fillWidth: trueandLayout.preferredWidthfor fluid, DPI-adaptive interfaces. - Virtualized Views (
ListView,TableView): Avoid heavyQtQuick.Layoutsinside delegates due to overhead during scrolling. Use lightweight Positioners (Row,Column) or explicit anchors. - Never anchor immediate children of a Layout: Do not set
anchorsor bindx/y/width/heightdirectly on layout children. - Animations in Layouts:
- Rendering animations (
opacity,scale,rotation) can be applied directly to layout children. - Geometry animations must animate an inner child wrapped inside an outer
Itemthat providesLayout.preferredHeight: innerContent.implicitHeight.
- Rendering animations (
Resource & Scene Graph Optimization
- Eliminate Superfluous Visual Nodes: Use a plain
Iteminstead ofRectanglefor non-rendering containers, wrappers, or spacers to avoid unnecessary scene graph nodes inQRhi. - Asynchronous Image Loading: Set
asynchronous: trueandcache: trueonImage. Always specifysourceSize.widthandsourceSize.heightfor raster assets to prevent allocating massive textures in GPU VRAM. - Deferred Loading: Wrap heavy popups, dialogs, or subpages in
LoaderorStackLayoutto preserve instantaneous application startup. - Style Customization: Set
qputenv("QT_QUICK_CONTROLS_STYLE", "Basic");or"Fusion"before creatingQGuiApplicationif custom styling is needed on Windows (native styles rejectbackground/contentItemcustomization).
4. QML Coding Conventions
- Order of Members:
id(must always be first line)- Property declarations (
property int ...) - Signal declarations (
signal ...) - JavaScript helper functions
- Object properties (geometry, appearance, states)
- Child visual objects
- Identifier Naming:
PascalCasefor QML files/types (CustomButton.qml).camelCasefor properties, IDs, signals, and functions.- CRITICAL: NEVER use
on+ Uppercase for property names (e.g.property color onPrimary). The parser interprets this as a signal handler forsignal Primary()and throwsCannot assign a value to a signal. UsecolorOnPrimaryortextPrimaryinstead.
- Signal Handlers in Qt 6: Use arrow function syntax with explicit parameter names:
MouseArea { onClicked: mouse => { console.log(mouse.x, mouse.y); } } - Modern
ConnectionsSyntax:Connections { target: backendService function onErrorOccurred(code: int, message: string) { notification.show(message); } } - Localization: Wrap every user-visible string in
qsTr()as it is written.
5. Windows MSBuild & Qt Tooling Architecture
The MSBuild Division of Labor
- Qt Visual Studio Tools ships MSBuild rules for
moc,uic, andrcconly. - There is NO built-in QML Compiler switch in Visual Studio Qt Project Settings. All QML tooling (
qmllint,qmlcachegen,qmltyperegistrar) must be driven via custom MSBuild targets.
The Recommended Target Pipeline (QtQml.targets)
Import QtQml.targets as the last item in your .vcxproj:
QmlPrepareItems ──► QmlTypeInfo ──► QmlLint (BeforeTargets=PrepareForBuild)
└───► QmlCacheGen ──► QmlCacheLoader ──► QmlCompileGenerated
(BeforeTargets=ClCompile)QmlPrepareItems: Runs every build; globs QML and C++ model headers and derives.cppoutput and resource paths.QmlTypeInfo: Runsmoc --output-jsonper model header +qmltyperegistrarto generate.qmltypesandqmldir. Feeds-I <IntDir>qmltypesto bothqmllintandqmlcachegenso C++ types are recognized at build time.QmlLint: Executesqmllintacross all QML files before compilation (BeforeTargets="PrepareForBuild"). Errors fail the build. Configure severities in.qmllint.ini(e.g.,UnqualifiedAccess=disablefor migrating legacy scopes).QmlCacheGen(AOT): Ahead-of-Time compiles QML documents into C++ units (<file>_qml.cpp).- Default:
QmlAotEnabled=falsein Debug (fast incremental developer workflow) andtruein Release (~3.6x cold-cache startup speedup).
- Default:
QmlCacheLoader: Generatesqmlcache_loader.cppusing a response file (@file.rsp). Contract: The loader response file entries must match the exactqrc:resource paths loaded by the engine (not filesystem paths), or lookups silently miss.QmlCompileGenerated: Injects generated.cppunits intoClCompilebefore compilation.
Critical MSBuild Flags for Generated QML Sources
Generated .cpp units require specific compilation metadata:
AdditionalOptions=/Zc:__cplusplus /utf-8: Required by MSVC so__cplusplusmatches C++17/20; without it Qt'sqcompilerdetection.hfails with#error: Qt requires a C++17 compiler.PrecompiledHeader=NotUsing: Generated units do not include projectpch.h.AdditionalIncludeDirectories=$(QmlQtIncludeDir): Points to<Qt>/includeso module-prefixed headers (<QtQml/qqmlprivate.h>) resolve.Condition="'$(DesignTimeBuild)' != 'true'": Prevents running slow tooling passes during Visual Studio IntelliSense design-time background builds.- Build the
.sln: Always build the solution or pass/p:SolutionDir=<dir>\to prevent sibling project include paths from breaking.
6. Anti-Patterns & Pitfalls Checklist
| Pitfall | Symptom / Consequence | Required Fix |
Component.onCompleted property assignments | Double-evaluation, breaks reactivity, delayed runtime errors | Use declarative property bindings instead |
target: parent in animation elements | ReferenceError: parent is not defined | Animations inherit QObject, not QQuickItem. Set target by explicit id |
Role lookup by hardcoded number (0x0106) | Silent data corruption when roles are inserted | Expose roles with Q_ENUM and reference TypeName.RoleName |
| Accessing GUI QObjects from worker thread | Intermittent memory corruption / crash | Transfer data via Qt signals/slots or QMetaObject::invokeMethod(..., Qt::QueuedConnection) |
| Omitting setter equality guards | Infinite binding loops, CPU spikes | Guard every setter with if (_field == value) return; |
Passing unparented QObject* to QML | Crash via premature garbage collection | Ensure C++ parent exists or set explicit C++ ownership |
| Capturing QML visual items in JS closures | Memory leak; crash on asynchronous access | Avoid item capture in long-lived timers or callbacks |
qmllint missing type cascade | Hundreds of [import]/[unresolved-type] warnings | Generate .qmltypes via moc --output-json + qmltyperegistrar |
| Cache loader keyed by source path | Silent AOT failure (engine loads bytecode) | Pass qrc: resource paths in the loader response file |
7. Deep Reference Documentation
For in-depth explanations, command-line arguments, empirical benchmarks, and configuration templates, consult the reference documents in this skill's references/ directory:
- Modern Qt 6 QML Best Practices: Full architectural guide covering typing pragmas, MVVM separation, layouts, responsive design, styling, and memory models.
- Qt Tooling in an MSBuild Project: Full technical manual for driving
qmllint,qmlcachegen,qmltyperegistrar, andmocfrom Visual Studio MSBuild without CMake, including upgrade checklists and troubleshooting gotchas.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

