Essential QWidget Properties and Controls for Qt C++ Development

Common Controls and Properties

Property Description
enabled Controls whether the widget is interactive. True means the widget is active, false disables user interaction.
geometry Position and dimensions, comprising x, y, width, and height. Coordinates are relative to the parent element.
windowTitle Sets the widget's title bar text.
windowIcon Sets the icon displayed in the title bar.
windowOpacity Controls the window's transparency level.
cursor Defines the cursor shape displayed when hovering over the widget, such as arrow, wait, or crosshair. Qt Designer shows all available options.
font Font-related properties including family, size, bold, italic, and underline styles.
toolTip Brief help text displayed in the status bar when hovering over the widget.
toolTipDuring Duration in milliseconds for which the tooltip remains visible.
statusTip Status message shown when the widget's state changes, such as when a button is pressed.
whatsThis Extended help information displayed when hovering and pressing F1, shown in a popup window.
styleSheet Allows CSS-style styling for widgets. Qt supports a rich subset of CSS properties familiar to web developers.
focusPolicy Determines how the widget receives keyboard focus. Qt:NoFocus: Widget cannot receive focus through keyboard or mouse Qt:TabFocus: Widget receives focus via Tab key Qt:ClickFocus: Widget receives focus via mouse click Qt:StrongFocus: Widget accepts focus from both keyboard and mouse Qt:WheelFocus: Widget accepts focus via mouse wheel (may not work on all platforms)
contextMenuPolicy Controls context menu display behavior. Qt:DefaultContextMenu: Standard context menu triggered by right-click or keyboard shortcut Qt:NoContextMenu: Disables context menu entirely Qt:PreventContextMenu: Prevents context menu display Qt:ActionsContextMenu: Replaces context menu with the widget's actions menu Qt:CustomContextMenu: Triggers a custom context menu
locale Sets language and regional settings.
acceptDrops Enables drag-and-drop functionality. When true, the widget can receive dropped items and processes dropEvent accordingly.
minimumSize Minimum dimensions for the widget, including minimum width and height.
maximumSize Maximum dimensions for the widget, including maximum width and height.
sizePolicy Size policy defining how the widget expands or shrinks within layout managers.
windowModality Specifies whether the window behaves as a modal dialog.
sizeIncrement Step size for window resizing operations.
baseSize Base size used in conjunction with sizeIncrement to calculate appropriate widget dimensions.
palette Color scheme for the widget's appearance.
mouseTracking Enables continuous mouse move events. When true, the widget receives mouseMoveEvent as the cursor passes through; when false, only mousePress and mouseRelease events are generated.
tabletTracking Enables tracking for touchscreen move events. Similar to mouseTracking, introduced in Qt 5.9.
layoutDirection Text flow direction. Qt:LeftToRight: Default left-to-right text layout Qt:RightToLeft: Right-to-left text layout Qt:GlobalAtomics: Layout direction determined by application-wide atomic settings
autoFillBackground Enables automatic background color filling.
windowFilePath Associates the widget with a local file path.
accessibleName Accessibility name read by assistive technologies like screen readers, essential for implementing accessible applications.
accessibleDescription Detailed accessibility description, used alongside accessibleName.
inputMethodHints Input hints for text fields, specifying acceptable input formats such as numeric-only or date-only entry.

1.QWidget Core Properties

①enabled Property

The enabled property indicates whether a widget accepts user input. Disabled widgets typically appear grayed out and cannot receive any input events. When a parent widget is disabled, all its child widgets are also disabled.

API Description
isEnabled() Returns the current enabled state as a boolean.
setEnabled(bool enabled) Sets the widget's enabled state. True enables interaction, false disables it.

Disabled widgets cannot be clicked and display in a grayed appearance.

Controlling Widget Availability with Buttons

When designing interfaces with multiple controls, ensure each widget has a unique objectName. Qt Designer generates a ui_widget.h file that maps these names to widget instances, accessible via ui->objectName syntax. The default naming convention (pushButton, pushButton_2, etc.) is not ideal for maintenance—consider renaming to descriptive identifiers in the property editor.

②geometry Property

The geometry property encompasses four values: x coordinate, y coordinate, width, and height. While these values can be accessed individually, Qt provides convenient wrapper methods for common operations.

| || | API | Description (Returns QRect Rectangle) | | geometry() | Retrieves position and dimensions as a QRect containing x, y, width, and height. Coordinates specify the top-left corner. | | setGeometry(QRect rect) setGeometry(int x, int y, int width, int height) | Sets position and dimensions using either a QRect or four separate integer parameters. |

The following example demonstrates geometry manipulation through button interactions:

void MainWindow::onIncreaseButtonClicked()
{
    ui->label->setText("Resized");
}

// Move on button release
void MainWindow::onMoveButtonReleased()
{
    // Calculate random position within window bounds
    int windowWidth = this->geometry().width();
    int windowHeight = this->geometry().height();
    
    // Seed random number generator once, typically in constructor
    int randomX = rand() % windowWidth;
    int randomY = rand() % windowHeight;
    
    ui->statusLabel->setText("Position updated");
    ui->moveButton->move(randomX, randomY);
}

// Move immediately on button press
void MainWindow::onMoveButtonPressed()
{
    int windowWidth = this->geometry().width();
    int windowHeight = this->geometry().height();
    
    int randomX = rand() % windowWidth;
    int randomY = rand() % windowHeight;
    
    ui->statusLabel->setText("Moving...");
    ui->moveButton->move(randomX, randomY);
}

③Window Frame Coordinate Calculations

When a QWidget operates as a top-level window (with title bar and minimize/maximize/close buttons), two distinct coordinate systems apply: one including the window frame and one excluding it.

Methods including window frame in calculations: x(), y(), frameGeometry(), pos(), move()

Methods excluding window frame: geometry(), width(), height(), rect(), size()

For non-window widgets, both approaches yield identical results.

API Description
x() Horizontal position, including window frame.
y() Vertical psoition, including window frame.
pos() Returns QPoint with x(), y(), setX(), setY() methods. Includes window frame.
frameSize() Returns QSize with width(), height(), setWidth(), setHeight() methods. Includes window frame.
frameGeometry() Returns QRect combining position and size. Includes window frame.
width() Widget width without window frame.
height() Widget height without window frame.
size() Returns QSize without window frame.
rect() Returns QRect without window frame, positioned at (0,0) relative to widget content.
geometry() Returns QRect without window frame, representing client area.
setGeometry() Sets position and size without window frame consideration.

Note: In the constructor, before the widget is fully realized, these values appear identical. The geometry rectangle is consistently smaller than frameGeometry by the window frame dimensions.

④windowTitle Property

Applies only to top-level windows with title bars.

API Description
windowTitle() Retrieves the current window title.
setWindowTitle(const QString& title) Sets the window title text.

⑤windowIcon Property

Applies only to top-level windows with title bars.

API Description
windowIcon() Returns the current window icon as a QIcon object.
setWindowIcon(const QIcon& icon) Sets the window icon.

QIcon objects are lightweight. Creating them on the stack is acceptable since Qt manages memory through object trees. Absolute file paths cause portability issues—use relative paths or Qt's resource system instead.

Qt Resource Collection (qrc) System

The qrc mechanism embeds binary image data directly into the compiled executable. Create an XML file with .qrc extension listing resources to include. During compilation, Qt extracts image data and converts it to C++ code integrated into the final binary.

Implementation steps: Create a qrc file in your project, add image files from subdirectories of the qrc location, and reference images using the : prefix notation. This approach eliminates path dependency issues but is unsuitable for very large resources.

⑥windowOpacity Property

API Description
windowOpacity() Returns opacity level as float from 0.0 (fully transparent) to 1.0 (fully opaque).
setWindowOpacity(float opacity) Sets the window opacity level.

The following demonstrates opacity adjustment through button controls:

void WindowController::onFadeInClicked()
{
    float currentOpacity = windowOpacity();
    if (currentOpacity >= 1.0f) {
        return;  // Prevent unnecessary calculations
    }
    
    float newOpacity = currentOpacity + 0.1f;
    setWindowOpacity(newOpacity);
}

void WindowController::onFadeOutClicked()
{
    float currentOpacity = windowOpacity();
    if (currentOpacity <= 0.0f) {
        return;  // Defensive programming practice
    }
    
    float newOpacity = currentOpacity - 0.1f;
    setWindowOpacity(newOpacity);
}

Developers should avoid direct floating-point equality comparisons like (opacity <= 0.0) for boundary checks in calculations. Floating-point precision issues mean 0.1 + 0.2 does not equal 0.3 exactly, following IEEE 754 representation standards. The defensive programming approach shown above prevents edge case issues from propagation.

⑦cursor Property

API Description
cursor() Returns the current cursor shape as QCursor.
setCursor(const QCursor& cursor) Sets cursor shape, effective only when mouse hovers over this widget.
QGuiApplication::setOverrideCursor(const QCursor& cursor) Sets a global cursor override affecting all widgets, superseding individual setCursor calls.

Creating Custom Cursors

Load a custom image through Qt's resource system, then construct a QCursor from the pixmap:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPixmap>
#include <QCursor>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    // Load image from resource system
    QPixmap customImage(":/resources/cursor_image.png");
    
    // Scale image if necessary (returns new scaled pixmap)
    customImage = customImage.scaled(64, 64, Qt::KeepAspectRatio);
    
    // Create cursor with custom hotspot at offset (10, 10)
    QCursor customCursor(customImage, 10, 10);
    
    setCursor(customCursor);
}

MainWindow::~MainWindow()
{
    delete ui;
}

Built-in Cursor Shapes

Qt provides predefined cursor shapes through the Qt::CursorShape enumeration:

enum CursorShape {
    ArrowCursor,
    UpArrowCursor,
    CrossCursor,
    WaitCursor,
    IBeamCursor,
    SizeVerCursor,
    SizeHorCursor,
    SizeBDiagCursor,
    SizeFDiagCursor,
    SizeAllCursor,
    BlankCursor,
    SplitVCursor,
    SplitHCursor,
    PointingHandCursor,
    ForbiddenCursor,
    WhatsThisCursor,
    BusyCursor,
    OpenHandCursor,
    ClosedHandCursor,
    DragCopyCursor,
    DragMoveCursor,
    DragLinkCursor,
    LastCursor = DragLinkCursor,
    BitmapCursor = 24,
    CustomCursor = 25
};

⑧font Property

API Description
font() Returns current font settings as QFont object.
setFont(const QFont& font) Applies new font settings to the widget.

QFont Key Properties

Property Description
family Font family name such as "Arial", "Times New Roman", or "Microsoft YaHei".
pointSize Font size in points.
weight Font weight from 0 to 99, higher values indicate bolder appearance.
bold Boolean flag equivalent to weight of 75 when true, 50 when false.
italic Enables italic style.
underline Enables underline decoration.
strikeOut Enables strikethrough decoration.

⑨toolTip Property

API Description
setToolTip(const QString& tip) Sets tooltip text displayed when hovering.
setToolTipDuration(int duration) Sets tooltip display duration in milliseconds.

Tooltips are purely informational for users and rarely accessed programmatically.

⑩focusPolicy Property

Focus determines which widget receives keyboard input. This is essential for text fields, radio buttons, and checkboxes. Pressing Tab cycles through focusable widgets based on their focus policy.

API Description
focusPolicy() Returns current focus policy as Qt::FocusPolicy.
setFocusPolicy(Qt::FocusPolicy policy) Sets the widget's focus acquisition behavior.

Qt::FocusPolicy Enumeration Values

  • Qt::NoFocus: Widget never receives keyboard focus
  • Qt::TabFocus: Widget gains focus through Tab key
  • Qt::ClickFocus: Widget gains focus through mouse click
  • Qt::StrongFocus: Widget gains focus through Tab or click (default behavior)
  • Qt::WheelFocus: Similar to StrongFocus, additionally accepts focus via scroll wheel

⑪styleSheet Property (CSS for Qt)

Qt Style Sheets (QSS) adapt CSS concepts for widget styling. Properties control visual aspects including size, position, color, spacing, fonts, backgrounds, and borders. The syntax mirrors CSS with key-value pairs separated by colons and declarations terminated by semicolons.

QPushButton {
    background-color: #3498db;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
}

QPushButton:hover {
    background-color: #2980b9;
}

QLineEdit {
    border: 1px solid #bdc3c7;
    padding: 4px;
    font-family: Arial;
    font-size: 14px;
}

Refer to Qt's "Qt Style Sheets Reference" documentation for the complete list of supported properties. Invalid property names produce no errors but simply fail to apply styling.

Tags: Qt QWidget cpp GUI-Development qt-creator

Posted on Thu, 18 Jun 2026 17:13:43 +0000 by majik-sheff