Repository navigation
code_style
This page is how QElectroTech's C++ code is written, so that a change reads like the code around it and a reviewer can look at what it does rather than how it is laid out.
Each rule here is one of two kinds:
- Current β what the code already does almost everywhere. Follow it.
- New code β a best-practice improvement, used where the code today is mixed or old-fashioned. Use it in code you write; do not go back and change old code to it in the same pull request.
The rules were measured on master at commit dab5e1f32 (2026-10-30): 915
.cpp/.h files under sources/, not counting the bundled third-party code.
The counts are given so you can see how firm each rule is.
This page is about source code. For the layout rules an AI assistant follows when it draws a schematic, see Your house style.
- Match the code around you. If a file does something differently from this page, the file wins inside that file.
- Never reformat lines you are not changing. A pull request where half the diff is whitespace cannot be reviewed. Format only your own lines (Formatting with clang-format shows how).
- One tab per indent level, 80 columns, English everywhere β in the interface text, in comments and in names.
| Rule | Kind | Measured |
|---|---|---|
File names are all lowercase, no underscores: class DiagramView lives in diagramview.h / diagramview.cpp
|
Current | 9 files of 915 have an underscore |
One class per .h/.cpp pair, named after the class |
Current | |
Include guards #ifndef DIAGRAMVIEW_H / #define DIAGRAMVIEW_H, not #pragma once
|
Current | 459 headers to 1 |
| Every file starts with the GPL licence block below | Current | 879 of 915 files |
Add // SPDX-License-Identifier: GPL-2.0-or-later on the line after the block |
New code | 25 files already do |
| UTF-8 without a byte-order mark, Unix line endings (LF) | New code | 35 files have a BOM, 2 have CRLF β don't add more, don't strip them in passing |
| No trailing spaces or tabs on lines you write | New code | 7,054 lines have them today |
The licence block, with the current year:
/*
Copyright 2006-2026 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-2.0-or-later
#include "diagramview.h"Includes. The file's own header first, then QET headers in "quotes",
then Qt and standard headers in <angle brackets>, a blank line between the
groups. Include the Qt class you use (<QHash>), not a whole module
(<QtWidgets>). Do not reorder existing include lists β it creates diff
noise and can hide a missing include.
| Rule | Kind | Measured |
|---|---|---|
| Indent with tabs, one per level; a tab is shown 4 columns wide | Current | 98.5 % of indented lines |
| Keep lines to 80 columns (tab = 4) | Current | 94 % of lines fit |
| Function and class bodies: brace on its own line | Current | 87 % of function definitions |
if / for / while / switch: brace on the same line
|
Current | 74 % of control statements |
} else { on one line |
Current | |
A space after if, for, while, switch: if (x)
|
Current | |
case labels indented one level inside switch
|
Current | 206 switches to 13 |
public: / private: indented one level inside the class, members two |
Current | 1,507 to 28 |
Pointer and reference stick to the name: Element *elmt, const QString &name
|
Current | 4,165 to 41; 2,336 to 195 |
No space after !: if (!elmt)
|
Current | 4,950 to 20 |
No lining up of = or names in columns |
Current | almost none in the code |
| Constructor initialisers: colon at the end of the line, one per line | Current | |
Put the body of an if on its own line, and use braces when it is more than one line |
New code | |
No whole function on one line in a .cpp
|
New code | only 8 today; reviewers ask for them to be split |
What that looks like (an illustration, not code from the repository):
ElementScene::ElementScene(QETElementEditor *editor, QObject *parent) :
QGraphicsScene(parent),
m_qgi_manager(this),
m_element_editor(editor)
{
setItemIndexMethod(NoIndex);
}
int ElementScene::countTerminals(const QList<QGraphicsItem *> &items) const
{
if (items.isEmpty())
return 0;
int count = 0;
for (QGraphicsItem *item : items) {
switch (item->type()) {
case PartTerminal::Type:
++count;
break;
default:
break;
}
}
return count;
}and a class:
class ElementScene : public QGraphicsScene
{
Q_OBJECT
public:
explicit ElementScene(QETElementEditor *editor,
QObject *parent = nullptr);
~ElementScene() override;
int countTerminals(const QList<QGraphicsItem *> &items) const;
signals:
void partsAdded();
private:
QETElementEditor *m_element_editor = nullptr;
bool m_dirty = false;
};A long call breaks after a comma and continues one extra tab in, not lined up under the opening bracket:
connect(qApp, &QApplication::lastWindowClosed,
this, &QETApp::checkRemainingWindows);| What | Style | Example | Kind |
|---|---|---|---|
| Class, struct, enum type | PascalCase | TerminalStripModel |
Current |
| Class with a QET-wide meaning |
QET prefix |
QETProject, QETApp
|
Current |
| Function, method, slot, signal | camelCase | updateLabels() |
Current β 5,136 to 236 old snake_case methods |
| Data member |
m_ + lower_snake_case |
m_element_editor |
Current for new members β 1,362 to 414 old unprefixed ones |
| Local variable, parameter | lower_snake_case or camelCase, as the file does | cache_path |
Current (both are common) |
| Enum value | PascalCase | BringForward |
Current |
| New enum | enum class |
enum class Side { Left, Right }; |
New code β 28 today, 104 plain enum
|
| Getter / setter |
name() / setName(), a bool as isVisible() / hasMirror()
|
setHorizontalMirror() |
Current |
| Macro | ALL_CAPS, and avoid them | QETAPP_COMMON_TBT_PROTOCOL |
Current |
Do not rename old snake_case methods or unprefixed members while you are
fixing something else. A rename is its own pull request, if it is worth one.
Doxygen block above each function definition, in the .cpp. This is the
project's form (5,329 @brief against 6 \brief):
/**
@brief Diagram::adjustSceneRect
Grow the scene rect so it holds every item and the title block.
@param margin : extra space around the items, in scene units
@return true if the rect changed
*/
bool Diagram::adjustSceneRect(qreal margin)-
@briefnames the function asClass::method, then the description on the next lines, then@param name : β¦and@return β¦. - Document what a function does and why a caller would want it, not how β the code says how.
- Inside a function, comment why, not what: the reason for a workaround, the bug number it fixes, the case that broke before.
- Write
// commentwith a space after the slashes (new code β today it is split almost evenly). -
English only. Some old comments carry a French copy after
\~French; don't add new ones. -
TODOandFIXMEsay what is missing and, if there is one, the issue number:// TODO #1158: limit per terminal. - Delete code; don't comment it out. Git keeps the old version.
QElectroTech is C++17 and builds against Qt 6 only.
| Use | Not | Kind | Measured |
|---|---|---|---|
nullptr |
NULL, 0
|
Current | 2,012 to 173 |
override on every overriding function, without virtual
|
virtual on the override |
Current | 1,438 override
|
Range-for: for (Element *e : elements)
|
foreach / Q_FOREACH (deprecated in Qt 6) |
Current | 2,105 to 391 old ones |
Function-pointer connect(a, &A::sig, b, &B::slot)
|
SIGNAL() / SLOT() strings |
Current | 1,495 to 1 |
A lambda in connect always gets a context object: connect(a, &A::sig, this, [this]{ β¦ })
|
a lambda with no context | New code | 302 lambdas today |
signals: and emit
|
Q_SIGNALS / Q_EMIT
|
Current | |
static_cast<int>(x) |
(int)x |
Current | 408 to 23 |
qobject_cast<T *>() for QObjects |
dynamic_cast for QObjects |
New code | evenly split today |
QStringLiteral("β¦") for fixed strings |
building a QString from a plain literal each call |
Current | 4,731 |
auto where the type is already on the line (auto *w = new QWidget(this);, iterators) |
auto that hides what a variable is |
Current | |
In-class member initialisers: bool m_dirty = false;
|
setting every member in each constructor | New code | 768 already |
const & for QString, QList, and other non-trivial parameters |
passing them by value | Current | |
Q_ASSERT for things that cannot happen |
silently ignoring them | New code | 11 today |
- A
QObjector widget gets a parent when it is created. The parent deletes it. - Something you only point at and do not own, that may be deleted elsewhere,
is held as
QPointer<T>. - Something you own that has no parent is held in
std::unique_ptr<T>(orQScopedPointer<T>where the file already uses it), not a raw pointer with adeletein the destructor. - A bare
newwith no parent and no smart pointer needs a comment saying who deletes it.
Anything the user does to a project β moving, adding, removing, editing a
property β goes through a QUndoCommand pushed on the project's undo stack,
so that Edit βΊ Undo works and the project is marked changed. Don't change
items directly from a dialog or a slot. If a command must merge with the next
one (dragging, typing), give it an id; the ids in use are listed in
dev_doc/ID_of_QUndoCommand.txt.
-
qWarning()for something that went wrong and someone should know about. -
qDebug()only while you work: take it out before the pull request, or leave only lines that help diagnose a real report. - Never show a message box from code that can run without a window (command-line export, scripting).
The source language of the interface is English (since PR #1390, October 2026). Translators work from the English text.
-
Every string the user can see goes through
tr()(orQCoreApplication::translate()outside aQObject). -
Write the English text in the source. Never write French (or any other language) in
tr(). -
Use placeholders, never glue sentences together β word order differs between languages:
// Yes tr("Folio %1 of %2").arg(index).arg(total) // No tr("Folio ") + QString::number(index) + tr(" of ") + QString::number(total)
-
Counts use the plural form, so every language can get it right:
tr("%n element(s) selected", nullptr, count)
-
Use the second argument to tell translators what a short word means:
tr("Open", "verb: open a file"). -
Name menus, buttons and dialogs the way they already appear β check the existing
tr("β¦")text, don't guess. -
File names, XML tags, settings keys and log messages are not translated.
The .clang-format file in the repository is older than most of the code and
disagrees with it on the points below. Run on whole files it rewrites
30β80 % of the lines (measured: diagram.cpp 1,847 of 4,085 lines,
element.h 376 of 462). So:
Never run
clang-format -ion a whole file, and never with the repository's.clang-formatwithout checking each change against this page.
| The code does (this page) | The repository's .clang-format does |
|
|---|---|---|
| Pointer / reference | Element *e |
Element* e |
case labels |
indented inside switch
|
not indented |
public: / private:
|
indented one level | not indented |
| Control-statement brace | if (x) { |
{ on its own line |
| Not | !e |
! e |
Short if / case
|
body on the next line | joined onto one line |
| Assignments and declarations | not lined up | lined up in columns |
| Includes | left in the order they are | regrouped and sorted |
The same small function written carelessly, then formatted by each:
// written
int newHelper(Element* e,int x){ if(!e) return 0; switch(x){case 1: return 2; default: return x;} }// with the house style below: matches the code
int newHelper(Element *e, int x)
{
if (!e)
return 0;
switch (x) {
case 1:
return 2;
default:
return x;
}
}// with the repository's .clang-format: does not
int newHelper(Element* e, int x)
{
if (! e) return 0;
switch (x)
{
case 1: return 2;
default: return x;
}
}Save this as qet-house.clang-format outside your QET checkout (so it is
never committed by accident). It needs clang-format 14 or newer; it was
tested with clang-format 23.
# QET house style for clang-format: matches how the code is written.
# Use it on the lines you change only:
# git clang-format --style=file:/path/to/qet-house.clang-format
Language: Cpp
BasedOnStyle: LLVM
Standard: c++17
UseTab: Always
IndentWidth: 4
TabWidth: 4
ContinuationIndentWidth: 4
ColumnLimit: 80
BreakBeforeBraces: Custom
BraceWrapping:
AfterClass: true
AfterFunction: true
AfterControlStatement: Never
AfterEnum: false
AfterStruct: false
AfterNamespace: false
BeforeElse: false
BeforeCatch: false
SplitEmptyFunction: false
IndentAccessModifiers: true
IndentCaseLabels: true
NamespaceIndentation: All
IndentPPDirectives: AfterHash
PPIndentWidth: 4
PointerAlignment: Right
ReferenceAlignment: Right
SpaceAfterLogicalNot: false
SpaceAfterCStyleCast: false
SpaceBeforeParens: ControlStatements
AlignAfterOpenBracket: DontAlign
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignTrailingComments: true
SpacesBeforeTrailingComments: 1
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: Never
AllowShortBlocksOnASingleLine: Empty
AllowShortLoopsOnASingleLine: false
AllowShortLambdasOnASingleLine: Inline
BreakConstructorInitializers: AfterColon
PackConstructorInitializers: Never
ConstructorInitializerIndentWidth: 4
BreakInheritanceList: AfterColon
SpaceBeforeCtorInitializerColon: true
BinPackArguments: true
BinPackParameters: true
SortIncludes: Never
IncludeBlocks: Preserve
ReflowComments: false
FixNamespaceComments: false
MaxEmptyLinesToKeep: 2
KeepEmptyLinesAtTheStartOfBlocks: falseThis file is not in the repository yet; it is offered here so that formatting your own lines does not fight the code around them.
git clang-format (shipped with clang-format) formats only the lines that
differ from a commit, and leaves every other line alone:
# see what it would change in your work since master
git clang-format --style=file:$HOME/qet-house.clang-format --diff upstream/master
# apply it
git clang-format --style=file:$HOME/qet-house.clang-format upstream/masterRead the --diff output before applying it. A tool cannot know when a line
is laid out by hand on purpose (a table of values, a long connect).
Installing clang-format: on Debian and Ubuntu sudo apt install clang-format; on Windows it comes with the LLVM installer and with Visual
Studio's C++ tools; anywhere with Python, pip install clang-format gives a
recent version.
The project's original Qt Creator code style (tabs, 4 columns, access
specifiers and case labels indented) is
qtcreator-qet-style.xml,
described on the
old wiki.
Import it in Edit βΊ Preferences βΊ C++ βΊ Code Style with Importβ¦
(Tools βΊ Options in older Qt Creator versions). It agrees
with this page.
- The diff contains only lines you meant to change β no whitespace or
include-order changes elsewhere (
git diff upstream/master --statlooks the size you expect). - New files have the licence block, an include guard, no BOM.
- Tabs, 80 columns,
Type *name, braces as above. - New members are
m_β¦, new enums areenum class. - Every visible string is in
tr(), in English, with%1placeholders. - Changes to the project go through an undo command.
- No leftover
qDebug(), no commented-out code. - It builds without new warnings, and the tests pass (see Building from Source and the testing section of CONTRIBUTING.md).
- Contributing Code β fork, branch, pull request
- Building from Source
- Fix or add with an AI assistant
- CONTRIBUTING.md in the repository
Getting Started
π Languages β English Β· FranΓ§ais Β· Deutsch
Windows without admin rights β the portable archive, no installer
Guides
Conductors β wire properties, what feeds which export, cables, and hops where wires cross
Wires per terminal β limit the wires on a terminal, chain wiring instead of stars
Printing and exporting β paper, PDF, images, and what each path does differently
Linking elements β master, slave, terminal
PLC modules β I/O tables and linking a wire to a specific point
Using the element editor β drawing tools, saving, checks
Generic devices β a quick box symbol with terminals on any side, made by a wizard
Grid size and element size β why symbols aren't all the same scale, and scaling one without leaving the grid
Preferences reference β what each settings page does
Saving and loading settings β your whole setup in one file, to copy or keep
Keyboard-only control β mouseless QET, and what still needs a mouse
Mouse modifiers β what Shift, Ctrl and Alt change while you drag
3D mouse β SpaceMouse pan, zoom and buttons
Aligning items β snap symbols back to the grid, or line them up
Drawing aids β dark mode, snap and grid step, crosshair, dimensions, the tape measure
Symbols already on the sheet β select the same symbols, replace them, show a T-junction as a dot, update placed copies from the collections
Symbol texts β place the texts at nine points, fixed or free size, format painter, title block cells, GOST ESKD, %T
Wiring tools β automatic connections, the Connections toolbar, chained folio reports, a cable across wires
Symbols and parts β edit several symbols, relay contact display, grouped parts list
Device types β what a device is made of: check, place and change its parts, Device Navigator
Project languages and checks β languages in a project, cell origin, duplicate labels, the Check panel
Reports and lists β project lists to CSV/PDF, tables on a folio, label-printer export, symbol list
Pictures on a sheet β labels, crop, transparency, what they cost in the file
Arcs and curved wires β the Arc tool, pulling an arc in or out, rounding a corner with a fillet, dashed arcs for lighting layouts
Grouping items β select, move and copy several items as one
Finding your place on a sheet β go to a cell like B13 or 4-B7, keep the headers in sight, show the cell limits, zoom and pan
Showing and hiding kinds of items β hide texts, wire numbers, shapes, pictures, tables or cross-references on every sheet
Drawing faster β place without dragging, the S shortcut bar, command search, gestures
Customising QElectroTech β keys, toolbar size and contents, the gesture ring
Managing collections β folders, writability, building your own shortlist
Templates β reusable multi-element blocks, placed by double-click or drag
Search & Replace β bulk property changes
Building a nomenclature query β the BOM/summary table builder
Formula columns β build a calculated column in a parts list without writing SQL
Linking wires across pages β sheet reports
Variables & formulas β %f, %{label}, sequences
Auto-numbering β schemes, sequences, freezing
Terminal strips β strips, levels, bridges
Connectors β plugs and sockets as terminal strips or head-with-pins devices, device types, pin check, spare-pin plans
Title block templates β the .titleblock format
Title block alignment β place a title block inside or outside the sheet, left, centred or right
Plants and locations β list, rename, copy a plant, suggestions
Designations and structure boxes β IEC 81346 names, structure boxes, ==/++ levels, folio groups, company prefixes
Revisions, document kinds and drawing standard β revision list and table, IEC 61355 document kind, project standard
Importing EPLAN parts (.edz) β EPLAN Data Portal
DXF import & export β two unrelated features, one format; command-line export and layers
Project files β .qetz (zipped, the default) and .qet, what is inside, opening big projects faster, starting from a template
The one-file project, .qetdb β history of saves, repair, --query over many projects
Saving safely β previous versions, a project open elsewhere, damaged files, crash recovery
The project database β the working SQLite database built when a project opens
Development
Code style β the QET house style for C++, and formatting only the lines you change
Fix or add with an AI assistant β beginner build setup and a prompt that does the work
Check your change: qet-verify β run it before every pull request
Posting with an AI assistant β short, plain pull requests and replies
Translate with an AI assistant β draft the interface in your language, check it, send it
Making a how-to video β a short feature video from a checked story
Writing wiki pages with an AI assistant β the rules, and a checker to run before you push
Automating QET β CLI, XML formats, external tools
CLI Reference β command line usage
JavaScript Scripting β --run, geometry editing, undo
MCP server β let an AI assistant read, verify and edit projects
Connecting an AI assistant β setup for Claude, Copilot, Gemini, Codex, Cursor, LM Studio
Script buttons β stored scripts with an icon, by hand or by an assistant
Live mode β an assistant working in the open project while you watch
Macro recorder β record a task by hand, for an assistant to script
Vision β proposal, under discussion
