QLabel
QLabel serves as a versatile widget for presenting both text and images within a Qt interface.
Core Properties
| Property | Description |
|---|---|
| text | The textual content displayed |
| textFormat | Plain text, rich text (HTML), Markdown, or auto-detection |
| pixmap | Internal image storage |
| scaledContents | When enabled, content stretches to fill the label dimensions |
| alignment | Horizontal and vertical positioning |
| wordWrap | Automatic line breaking for lengthy text |
| indent | Text indentation (applies to one or two directions) |
| margin | Padding between content and border edges |
| openExternalLinks | Permit opening URLs embedded in text |
| buddy | Associated widget activated via keyboard shortcut |
Text Formatting Demonstration
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// Plain text formatting
ui->plainLabel->setTextFormat(Qt::PlainText);
ui->plainLabel->setText("# Plain text content");
// Rich text with HTML markup
ui->richLabel->setTextFormat(Qt::RichText);
ui->richLabel->setText("<b>Bold formatted text</b>");
// Markdown formatted content
ui->mdLabel->setTextFormat(Qt::MarkdownText);
ui->mdLabel->setText("# Markdown Content");
}
Widget::~Widget()
{
delete ui;
}
Image Display with Dynamic Resizing
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
QRect bounds = this->geometry();
ui->imageLabel->setGeometry(0, 0, bounds.width(), bounds.height());
QPixmap image(":/background.png");
ui->imageLabel->setPixmap(image);
ui->imageLabel->setScaledContents(true);
}
Widget::~Widget()
{
delete ui;
}
void Widget::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
ui->imageLabel->setGeometry(0, 0, event->size().width(), event->size().height());
}
Setting geometry once in the constructor produces a static label. To make the label respond to window resizing, override QWidget's resizeEvent. This leverages C++ polymorphism—Qt internally calls the base class method, but derived class implementation executes instead.
Text Alignment Configuration
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->labelCentered->setText("Centered Text");
ui->labelCentered->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->labelRightMid->setText("Right Middle");
ui->labelRightMid->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
ui->labelRightTop->setText("Right Top");
ui->labelRightTop->setAlignment(Qt::AlignRight | Qt::AlignTop);
ui->labelDefault->setText("Default Alignment");
}
Wrapping, Indentation, and Margins
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// Centered positioning
ui->labelOne->setText("Sample Text One");
ui->labelOne->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
// Word wrapping enabled
ui->labelWrap->setText("Extended text content that spans multiple lines when displayed");
ui->labelWrap->setWordWrap(true);
// Indentation applied
ui->labelIndent->setText("Indented text content demonstrating the indent feature");
ui->labelIndent->setWordWrap(true);
ui->labelIndent->setIndent(50);
// Margin spacing
ui->labelMargin->setText("Text with margin spacing");
ui->labelMargin->setWordWrap(true);
ui->labelMargin->setMargin(30);
}
The distinction: margin applies padding uniformly on all four sides, while indent affects at most two directions based on alignment settings.
Buddy Relationships
QLabel supports keyboard mnemonics using the ampersand character. Pressing Alt+key combination activates the associated buddy widget.
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// Mnemonic: Alt+O activates radioOption1
ui->labelOption1->setBuddy(ui->radioOption1);
// Mnemonic: Alt+T activates radioOption2
ui->labelOption2->setBuddy(ui->radioOption2);
}
In the UI designer, labels would contain text like "&Option1" and "&Option2" respectively.
QLCDNumber
QLCDNumber renders numerical displays mimicking vintage calculator aesthetics.
Key Properties
| Property | Purpose |
|---|---|
| intValue | Integer display value |
| value | Floating-point value (synced with intValue via rounding) |
| digitCount | Number of digit positions |
| mode | Dec, Hex, Bin, Oct display modes |
| segmentStyle | Flat, Outline, or Filled appearance |
| smallDecimalPoint | Compact decimal point rendering |
Decimal mode supports fractional display; other bases show integers only.
Countdown Timer Implementation
// widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void onTimeout();
private:
Ui::Widget *ui;
QTimer *countdownTimer;
};
#endif
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->lcdNumber->display("10");
countdownTimer = new QTimer(this);
connect(countdownTimer, &QTimer::timeout, this, &Widget::onTimeout);
countdownTimer->start(1000);
}
Widget::~Widget()
{
delete ui;
}
void Widget::onTimeout()
{
int current = ui->lcdNumber->intValue();
if (current <= 0) {
countdownTimer->stop();
return;
}
ui->lcdNumber->display(current - 1);
}
Why Not Use Loops or Threads?
A synchronous loop with sleep blocks the entire event loop, freezing the UI. Launching a separate thread to modify UI elements violates Qt's threading contract—GUI state changes must occur on the main thread to maintain consistency.
Qt widgets maintain complex internal state where modifying one element cascades through layout and positioning. Non-deterministic thread execution would corrupt this state.
The QTimer::timeout signal fires on the main thread, ensuring safe UI updates. Always prefer timers for periodic interface modifications.
QProgressBar
Progress bars indicate task completion status visually.
Properties Reference
| Property | Function |
|---|---|
| minimum | Lower bound value |
| maximum | Upper bound value |
| value | Current position |
| alignment | Text positioning within bar |
| textVisible | Display percentage text |
| orientation | Horizontal or vertical direction |
| invertAppearance | Reverse fill direction |
| textDirection | Text orientation |
| format | %p (percent), %v (raw value), %m (remaining ms), %t (total ms) |
Timed Progress Advancement
// widget.h
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void updateProgress();
private:
Ui::Widget *ui;
QTimer *progressTimer;
};
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
progressTimer = new QTimer(this);
connect(progressTimer, &QTimer::timeout, this, &Widget::updateProgress);
progressTimer->start(100);
}
Widget::~Widget()
{
delete ui;
}
void Widget::updateProgress()
{
int current = ui->progressBar->value();
if (current >= 100) {
progressTimer->stop();
return;
}
ui->progressBar->setValue(current + 1);
}
For actual file operations, calculate progress as (bytesRead / totalSize) * 100 and update accordingly.
QCalendarWidget
The calendar widget provides interactive date selection functionality.
Available Properties
| Property | Description |
|---|---|
| selectedDate | Currently selected date |
| minimumDate | Earliest selectable date |
| maximumDate | Latest selectable date |
| firstDayOfWeek | Day appearing in first column |
| gridVisible | Toggle cell borders |
| selectionMode | Single selection, no selection, etc. |
| navigationBarVisible | Show or hide the header bar |
| horizontalHeaderFormat | Date format in header row |
| verticalHeaderFormat | Row numbering format |
| dataEditEnabled | Allow direct date editing |
Relevant Signals
| Signal | Trigger Condition |
|---|---|
| selectionChanged(const QDate&) | Selected date modifies |
| activated(const QDate&) | Double-click date or press Enter |
| currentPageChanged(int, int) | Month or year navigation |
Date Selection Handler
// widget.h
#include <QWidget>
#include <QDate>
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void onDateSelected();
};
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->calendarWidget, &QCalendarWidget::selectionChanged,
this, &Widget::onDateSelected);
}
Widget::~Widget()
{
delete ui;
}
void Widget::onDateSelected()
{
QDate chosen = ui->calendarWidget->selectedDate();
qDebug() << chosen;
ui->dateLabel->setText(chosen.toString());
}
Connect the selectionChanged signal to a slot for real-time date processing. The selectedDate() method returns a QDate object convertible to various string formats via toString().