qt-widgets-to-quick¶
When to use
Ports Qt Widgets (QtWidgets, QWidget, QMainWindow, QDialog, .ui files, QPainter paintEvent) applications to Qt Quick: UI becomes QML with Qt Quick Controls and Qt Quick Layouts, custom QPainter widgets become QCanvasPainterItem + QCanvasPainterItemRenderer using QCanvasPainter (Qt 6.12+). Use whenever the user wants to migrate, port, convert, modernize or rewrite a Widgets application, window, dialog, custom widget or layout to QML / Qt Quick / Qt Quick Controls, or asks what the Qt Quick equivalent of a widget, layout, QAction, model view, QSS style sheet or paintEvent is. Do NOT trigger for new Qt Quick work with no Widgets source, for QPainter code that must stay on QtWidgets, or for Canvas2D (QML) drawing only (use qt-canvas2d).
Source: skills/qt-widgets-to-quick/SKILL.md
| compatibility | Designed for Claude Code, GitHub Copilot, and similar agents. Visual verification (comparing screenshots of the original and the port) needs a model that accepts image input; without one, the user compares them. |
| license | LicenseRef-Qt-Commercial OR BSD-3-Clause |
| category | procedural |
| qt-version | 6.12+ |
| version | 1.0 |
Qt Widgets → Qt Quick porting¶
Goal: turn a QtWidgets application into a Qt Quick application that looks and behaves the same, is idiomatic QML/C++, and builds cleanly.
| Widgets code | Becomes |
|---|---|
Widget UI, layouts, dialogs, menus, .ui |
QML + Qt Quick Controls + Qt Quick Layouts |
Custom QWidget with paintEvent / QPainter |
QCanvasPainterItem + QCanvasPainterItemRenderer using QCanvasPainter (Qt6::CanvasPainter, GPU, HTML-Canvas-like API) |
| Logic, models, I/O, networking, business classes | stays C++, exposed with QML_ELEMENT / QML_SINGLETON / Q_PROPERTY |
Do not answer API questions from memory. The references list the classes and
members that matter; for anything not listed, check the Qt docs (the qt-docs
MCP tools, if available) or the installed headers (include/QtCanvasPainter/).
How to apply¶
- Inventory the project (step 1) before writing anything.
- Read only the references you need (table below).
styling.mdis mandatory for any port with a UI. - Port in workflow order, building after each stage.
- Also use
qt-qmlfor the QML you write,qt-cmake-projectwhen restructuring CMake, andqt-canvas2d(itsreferences/api-reference.md) as a second source on painter semantics. - Verify (step 8). A port that was not built is not finished.
- Report what was mapped, what had no direct equivalent and what you chose, and what is left for the user (QSS visuals, native dialogs, …).
| Need | Read |
|---|---|
| Which Controls type replaces a widget; event → handler mapping | references/widget-mapping.md |
| Layouts, size policies, stretch, splitters, scroll areas, form layouts | references/layouts.md |
QMainWindow, menus, toolbars, dialogs, actions, .ui, main.cpp |
references/application-structure.md |
| C++ ↔ QML bridge, models, signals/slots | references/cpp-qml-integration.md |
| Style selection, palette, QSS, fonts, icons, High-DPI | references/styling.md |
QPainter / paintEvent code |
references/painting-qpainter-to-canvaspainter.md, references/custom-painted-items.md |
| CMake | references/cmake.md |
| Large or multi-window app, staged port, modal prompts, export, tests | references/large-app-porting.md |
QGraphicsScene as the document model, or QGraphicsView with many simple items |
references/graphics-view-to-canvaspainter.md |
| Many items per frame, slower than the original, benchmarking | references/performance.md |
| Worked before/after projects | examples/ (bottom of this file) |
Workflow¶
1. Inventory the source¶
Grep and write a short table (in your reasoning or the reply):
- Widget classes:
QWidget|QMainWindow|QDialog|QFrame|Q\w+(Edit|Box|Button|View|Widget|Bar|Menu|Label);.uifiles;.qss/setStyleSheet. - Custom painting:
paintEvent|QPainter|drawText|drawPixmap|QGraphicsView|QGraphicsScene|QOpenGLWidget(QOpenGLWidgetis not covered by QCanvasPainter; see "Hard cases"). - Input:
mousePressEvent|keyPressEvent|wheelEvent|eventFilter|dragEnterEvent|contextMenuEvent|resizeEvent. - Models:
QAbstractItemModel|QStandardItemModel|QSortFilterProxyModel|QStyledItemDelegate(usually reusable unchanged). - Logic to keep:
QTimer|QThread|QSettings|QTranslator|tr(. - Modal calls:
exec(),QMessageBox,QFileDialog,QInputDialog. - App setup that must survive:
setAttribute\(Qt::AA_|setNativeMenuBar(e.g.AA_DontUseNativeMenuBarkeeps menus in the window on macOS). - Compile-time macros in UI text:
QT_VERSION_STR|_VERSION\b|__DATE__(QML cannot see them; pass them from C++,application-structure.md). - Actions and shortcuts:
QAction|addAction|QShortcut|setShortcut|QKeySequencein C++, and<action name=…>/<addaction/<property name="shortcut">in.uifiles. Write one row per action: text, shortcut (literal orStandardKey), where it appears (menu, toolbar, context menu, or shortcut only), and the slot it triggers. Actions added only to the window (addAction(act)with no menu) are easy to miss. - Feature slots on the main window: in a monolithic
QMainWindowthe features are its slots (toUpperCase(),insertDate(),nextTab(), …). Every slot reached from the action table is a feature that must exist in the port, even though the class itself disappears.
Classify each UI class:
| Code | Target |
|---|---|
| Layout/composition of standard widgets | QML + Controls |
Custom widget painting with QPainter |
QCanvasPainterItem (C++) |
| Custom widget that only composes other widgets | reusable QML component |
| Non-UI logic (data, parsing, I/O, state machines) | keep as C++ QObject, expose to QML |
| Models | keep, use from QML views |
2. Decide the target structure¶
myapp/
CMakeLists.txt
main.cpp # QGuiApplication + QQmlApplicationEngine
Main.qml # was MainWindow
qtquickcontrols2.conf # style selection (styling.md)
components/*.qml # one per composed widget / dialog
backend/*.h|cpp # former non-UI C++ (QML_ELEMENT / QML_SINGLETON)
items/*.h|cpp # QCanvasPainterItem + renderer pairs
- One
qt_add_qml_modulefor the app: C++ types inSOURCES, QML inQML_FILES;QML_ELEMENTtypes then register automatically. - Load with
engine.loadFromModule("<Uri>", "Main")plus theobjectCreationFailed → exit(-1)guard (examples/*/main.cpp). - Keep widget class names for QML types (
AnalogClock), but never reuse the name of a built-in Controls type.
3. Port the application shell¶
QApplication → QGuiApplication; drop widget includes; QMainWindow →
ApplicationWindow (menuBar, header = ToolBar, footer = status bar).
Keep every setAttribute(Qt::AA_…) call; macros used in UI text
(QT_VERSION_STR) go to QML as an initial property or singleton property.
See references/application-structure.md.
4. Port layouts and standard widgets¶
Use widget-mapping.md and layouts.md. Habits:
- Always create
qtquickcontrols2.confand add it to CMake, mirroring the original: the style it set, or, if it set none, the platform default plus a+windows/qtquickcontrols2.confwithStyle=FluentWinUI3(Qt Quick's default Windows style does not match the Widgetswindows11style). State the choice in the report; no need to ask first (styling.md). - Import only
QtQuick,QtQuick.Controls,QtQuick.Layouts. Never import a style module (QtQuick.Controls.Universal,.Material, …): it pins the style at compile time. - Inside layouts use
Layout.fillWidth,Layout.preferredWidth, …, never barewidth:/anchors(seeqt-qml). - Preserve visible text exactly, including mnemonics (
&File), wrapped inqsTr(). Preserve tab order, default values, ranges, tooltips, enabled and visible state. - Port the widget's initial state, not the Controls default:
ListViewstarts at row 0 butQListWidgethas no current row (currentIndex: -1); date/time text uses the widget's format, by default the locale's short format, never raw ISO ("Default state differences" inwidget-mapping.md). setContentsMargins/spacing→Layout.margins,spacing,columnSpacing,rowSpacing; the outermost layout's margins go on the window content item.QLineEdit→TextField;QTextEdit→ScrollView { TextArea {} }. Fusion, FluentWinUI3 and the native styles draw a frame forTextAreathemselves; onlyBasicdraws none. Add abackgroundonly for a style that lacks one, and never underWindows/macOS(not customizable; it prints a warning).
5. Port business logic and models¶
- Keep non-UI classes; add
QML_ELEMENT(instantiable),QML_SINGLETON(global service) orQML_UNCREATABLE(C++-provided). - Logic inside the main window class is not dropped with the class. For a
monolithic
QMainWindow/QDialog, go through its slots (the feature list from step 1) and split each one: the widget-touching part (read selection, insert text, switch tab) becomes QML; the computation (case conversion, date formatting from settings, parsing, file handling) moves to a backendQObjectas aQ_INVOKABLEthat takes and returns plain values (QString toUpperCase(const QString &text)). Trivial one-liners may stay in QML JS. A slot you deliberately leave out goes into the report, never silently (large-app-porting.md, "Extract a widget-free controller first"). - Replace
connect(button, &QPushButton::clicked, …)withonClickedcalling aQ_INVOKABLE/slot, or with a binding to aQ_PROPERTY. C++ must not hold pointers to QML items: C++ emits signals or changes properties, QML reacts. - UI-only reactions (clear a field, toggle visibility) stay in QML; no C++ round trip.
QAbstractItemModelsubclasses are reused as-is byListView,TableView,TreeView(cpp-qml-integration.md).- Do not let exceptions propagate out of
Q_INVOKABLEs into the QML engine: catch and report via return value or signal (large-app-porting.md).
6. Port custom painting¶
For every paintEvent:
Foo : QCanvasPainterItem(GUI thread:QML_ELEMENT,Q_PROPERTYs, input,update()) plusFooRenderer : QCanvasPainterItemRenderer(render thread:paint());createItemRenderer()returns the renderer.- Copy all state the painting needs into renderer members in
synchronizeData(), the only point where both threads are synchronized.paint()must not touch the item. - Translate
QPaintercalls withpainting-qpainter-to-canvaspainter.md. Traps: rotation in radians (not forsetTransform(QTransform)); fill and stroke are explicit (no pen/brush state); path first;ellipse()takes centre + radii;fillColorclears the background every frame; images viaaddImageonce,drawImageper frame. Redrawing every item every frame can be slower than the original's dirty region repaint once hundreds of items are visible: batch the drawing (performance.md) and measure against the original before calling it done. - Mouse/keyboard: Pointer Handlers in QML around the item, or properties the
handlers write (
custom-painted-items.md).
7. Port visuals, resources, translations¶
QSS → Controls customization (styling.md); QIcon/.qrc →
qt_add_qml_module(RESOURCES …) + Image / icon.source; tr() → qsTr()
in QML (keep tr() in C++); .ts files keep working with
qt_add_translations.
8. Verify¶
In this order:
- Build the original first (
git archive <rev>into a scratch dir) and run it beside the port. Some behavioural differences were found only that way, not by reading code. - Configure and build (Windows: MSVC environment + Ninja; Qt prefix from the
project's
CMAKE_PREFIX_PATH; Qt'sbinonPATHwhen started from a script). Fix every warning that is yours. qmllint(-I <build dir>) andqmlformat -ion all QML.- Run the app for a few seconds. Any
is not a type,Cannot assign,Binding loopor other QML error on stderr is a defect (QT_FORCE_STDERR_LOGGING=1for Windows GUI apps;QT_LOGGING_TO_CONSOLEis deprecated in 6.12). - Compare screenshots with the Widgets original: text, order, stretch on
resize (grow, shrink to minimum, scroll), defaults. This needs a model that
can read images; if yours cannot, save both captures side by side, ask the
user to compare them, and say in the report that visual parity was not
checked by you. For captures use
QQuickWindow::grabWindow().save(...)from a throwaway harness; OS screen captures (CopyFromScreen) also worked for GPU windows when unobscured. For scripted input from outside, make the driver DPI-aware: with display scaling a DPI-unaware script gets cursor coordinates in logical pixels while screenshots are physical, and clicks land off target. - Check light and dark system mode (
QT_QPA_PLATFORM=windows:darkmode=0gives light on a dark Windows). Painted items take colors frompalette.*; hard-coded light colors that were fine in Widgets need a decision (follow the palette, or keep and mention). - Exercise each action, shortcut and dialog flow of the original, and every
mode of a custom view (hover, click, drag, modifiers, wheel, zoom limits).
Tick off the action table from step 1: every row must have a working
counterpart with the same shortcut, or a line in the report saying why not.
A click that does nothing:
QT_LOGGING_RULES=qt.quick.mouse.debug=true. - Custom views with many items: benchmark against the original
(
performance.md);QSG_RENDER_TIMING=1gives polish/sync/render per frame.
Rules¶
- No
QtWidgetsincludes orQt6::Widgetslinkage remain unless the user chose a hybrid port. LinkQt6::Quick; addQt6::CanvasPainteronly when aQCanvasPainterItemships (it pulls Widgets in transitively; that is fine, seecmake.md). - Never draw in the item class, read item/QObject state in
paint(), or call into QML from the render thread. - No style-specific imports; no hard-coded colors where a
palette.*role matches the widget'sQPaletterole. - Graphics View documents and large apps: port in stages with build and tests
green at each step, prove replacements against the Widgets behaviour, and look
at one real rendered frame per new window or overlay (
large-app-porting.md,graphics-view-to-canvaspainter.md). - Follow the project's license header and naming.
- Keep behavior identical first; improve afterwards and say so. Do not silently "fix" original quirks; mention them.
- If no Qt Quick equivalent exists, say so, pick the closest option from "Hard cases", and note the difference.
Hard cases (no 1:1 mapping)¶
Simple one-to-one widget replacements are in widget-mapping.md; these need a
decision.
| Source | Target |
|---|---|
QFormLayout |
two-column GridLayout (labels column 0, fields Layout.fillWidth) |
QGraphicsView/Scene, display-like, few items |
Qt Quick scene graph (items, Flickable, PinchHandler, DragHandler); custom item painting → QCanvasPainterItem |
QGraphicsView/Scene with many simple items (one item type, no hierarchy) |
plain-value model + grid index + one QCanvasPainterItem per view, frame recorded in updatePolish(), batched drawing ("Light variant", performance.md) |
QGraphicsView/Scene/Item as an editor document (hundreds+ items, hierarchy, selection, drag, hover) |
one QCanvasPainterItem + own model, spatial index and input dispatcher (graphics-view-to-canvaspainter.md) |
QGraphicsScene as document model under a Quick UI |
works headless, but keeps Qt6::Widgets + QApplication; replace in stages |
QOpenGLWidget / QRhiWidget |
QQuickRhiItem (or QQuickFramebufferObject for GL-only code) |
QTableWidget / QTreeWidget (item-based) |
model (QStandardItemModel or custom) + TableView / TreeView |
QTableView + delegate painting hundreds of columns |
one QCanvasPainterItem culling to the viewport, sharing a QItemSelectionModel (large-app-porting.md) |
QDockWidget, QMdiArea |
SplitView / Drawer / separate Windows; docking UX must be rebuilt |
QCustomPlot / Qt Charts widgets |
Qt Graphs (GraphsView) or a QCanvasPainterItem |
QSS :hover, gradients, custom controls |
Controls background / contentItem customization |
QPainter clip paths |
QCanvasPainter has only rectangular clip (setClipRect): fill the rounded shape instead, or pre-render |
QMessageBox::question / exec() deep in business code |
split at the prompt: request signal + respond(id, answer) continuation via a dialog-service singleton and DialogHost.qml; headless default answer; no nested event loop (large-app-porting.md) |
QTableView::grab(), QPrinter PDF export |
render the shared painter code to QImage / QPdfWriter (QtGui, no PrintSupport) |
findChild / objectName lookups (tours, spotlights) |
attached-property registry (Thing.name: "x"), one overlay per window |
| Event-filter helper painting and hit-testing handles over a widget | QML handle items + DragHandler + Q_INVOKABLE geometry on the item (custom-painted-items.md) |
Widget Q_PROPERTYs named rotation, scale, width, … |
rename; they clash with QQuickItem properties |
QApplication::font() / clipboard(), QToolTip::font() |
QGuiApplication::font() / clipboard() |
Hybrid fallback for apps too large to port in one go: QCanvasPainterWidget
moves a custom-painted widget to QCanvasPainter without leaving QtWidgets, and
QQuickWidget embeds finished QML inside an unported Widgets window.
Examples¶
examples/ holds four buildable projects. The *_quick folders are the
quality bar: no dead code, no style-specific imports, behavior identical to the
original.
| Folder | Shows |
|---|---|
analogclock_widgets/ |
Original: QWidget + QPainter + QTimer |
analogclock_quick/ |
QCanvasPainterItem + renderer, synchronizeData, radians, palette colors |
basiclayouts_widgets/ |
Original: group boxes, box/grid/form layouts, menu bar, scroll area |
basiclayouts_quick/ |
ApplicationWindow, MenuBar, GroupBox, GridLayout, ScrollView, style via conf, small C++ backend |