Qt Widgets模块功能详细说明,基本控件:QLabel(一)

一、基本控件(Widgets)

Qt 提供了丰富的基本控件,如按钮、标签、文本框、复选框、单选按钮、列表框、组合框、菜单、工具栏等。

1、QLabel

1.1、概述 (用途、继承关系)

QLabel 是 Qt 框架中用于显示文本、图像或动画的控件,属于轻量级界面元素,通常用于展示不可编辑的内容。它是用户界面中常见的组件,适用于显示提示信息、标题、图片或超链接等。

  • 显示静态文本(如标题、说明、提示信息)。

  • 显示图像(支持多种格式,如 PNG、JPG、GIF 等)。

  • 作为超链接容器(支持 HTML 格式的超链接)。

  • 用作其他控件的标签(如与输入框搭配的提示标签)。

  • 显示动态内容(如状态提示或动画)。

继承关系:

  • QLabel 继承自 QFrame,因此具备 QFrame 的边框、背景等属性。

  • QFrame 继承自 QWidget,因此 QLabel 也具备 QWidget 的通用属性和方法(如大小、位置、样式等)。

1.2、常用属性 (文本、图像、对齐方式、伙伴控件等)

  • 文本 (text):

    • 属性:text

    • 描述:设置或获取标签显示的文本内容,支持普通文本和富文本(HTML 格式)。

    • 示例:label->setText("Hello, Qt!");

  • 图像 (pixmap):

    • 属性:pixmap

    • 描述:设置标签显示的图像(QPixmap 对象),常用于显示静态图片。

    • 示例:label->setPixmap(QPixmap("image.png"));

  • 对齐方式 (alignment):

    • 属性:alignment

    • 描述:控制文本或图像在标签中的对齐方式,支持 Qt::Alignment 枚举值(如 Qt::AlignLeft、Qt::AlignCenter、Qt::AlignRight、Qt::AlignTop 等)。

    • 示例:label->setAlignment(Qt::AlignCenter);

  • 伙伴控件 (buddy):

    • 属性:buddy

    • 描述:将标签与另一个控件关联,通常用于表单界面中,通过快捷键(如 Alt+字母)激活伙伴控件(如 QLineEdit)。

    • 示例:label->setBuddy(lineEdit);(通常配合 & 符号,如 setText("&Name"))。

  • 自动换行 (wordWrap):

    • 属性:wordWrap

    • 描述:启用后,文本内容会根据标签宽度自动换行。

    • 示例:label->setWordWrap(true);

  • 缩放内容 (scaledContents):

    • 属性:scaledContents

    • 描述:启用后,图像会自动缩放以适应标签大小,可能会导致图像失真。

    • 示例:label->setScaledContents(true);

  • 文本格式 (textFormat):

    • 属性:textFormat

    • 描述:设置文本的格式,支持 Qt::PlainText(纯文本)、Qt::RichText(HTML 格式)或 Qt::AutoText(自动检测)。

    • 示例:label->setTextFormat(Qt::RichText);

  • 边距和缩进 (margin, indent):

    • 属性:margin、indent

    • 描述:控制标签内容与边框的间距(margin)或文本的缩进(indent)。

    • 示例:label->setMargin(10); 或 label->setIndent(5);

#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QPixmap>
#include <QLineEdit>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QWidget window;
    QVBoxLayout *layout = new QVBoxLayout(&window);

    //============================
    // 1. 文本 (text)
    //==============================
    QLabel *textLabel = new QLabel("<b>Hello, Qt!</b> This is a demonstration of QLabel properties.");
    layout->addWidget(textLabel);

    //================================
    // 2. 图像 (pixmap)
    //================================
    // 确保你的项目目录下有名为 "image.png" 的图片文件
    QLabel *pixmapLabel = new QLabel();
    QPixmap pixmap(":/images/save.png");
    if (!pixmap.isNull()) {
        pixmapLabel->setPixmap(pixmap);
        pixmapLabel->setScaledContents(true); // 配合 scaledContents
        pixmapLabel->setFixedSize(200, 150); // 设置固定大小以便缩放效果更明显
        layout->addWidget(pixmapLabel);
    } else {
        QLabel *errorLabel = new QLabel("Image file 'image.png' not found!");
        layout->addWidget(errorLabel);
    }

    //================================
    // 3. 对齐方式 (alignment)
    //================================
    QLabel *alignedLabel = new QLabel("This text is centered.");
    alignedLabel->setAlignment(Qt::AlignCenter);
    alignedLabel->setStyleSheet("border: 1px solid black;"); // 添加边框以便观察对齐效果
    layout->addWidget(alignedLabel);

    //===============================
    // 4. 伙伴控件 (buddy)
    //===============================
    QLabel *buddyLabel = new QLabel("Name(&N):");
    QLineEdit *lineEdit = new QLineEdit();
    buddyLabel->setBuddy(lineEdit);
    QHBoxLayout *buddyLayout = new QHBoxLayout();
    buddyLayout->addWidget(buddyLabel);
    buddyLayout->addWidget(lineEdit);
    layout->addLayout(buddyLayout);

    //==============================
    // 5. 自动换行 (wordWrap)
    //===============================
    QLabel *wordWrapLabel = new QLabel("This is a long sentence that will wrap automatically if the label is not wide enough.");
    wordWrapLabel->setWordWrap(true);
    wordWrapLabel->setStyleSheet("border: 1px solid blue;"); // 添加边框以便观察换行效果
    layout->addWidget(wordWrapLabel);


    // 6. 缩放内容 (scaledContents) - 已在 pixmap 示例中包含

    //====================================
    // 7. 文本格式 (textFormat)
    //====================================
    QLabel *htmlLabel = new QLabel();
    htmlLabel->setTextFormat(Qt::RichText); // 明确设置为富文本格式
    htmlLabel->setText("<h1>Rich Text Example</h1><p style='color:red;'>This is <span style='text-decoration: underline;'>HTML</span> formatted text.</p>");
    layout->addWidget(htmlLabel);

    QLabel *plainTextLabel = new QLabel();
    plainTextLabel->setTextFormat(Qt::PlainText); // 设置为纯文本格式,HTML标签会被直接显示
    plainTextLabel->setText("<h1>Plain Text Example</h1><p>This is <b>not</b> interpreted as HTML.</p>");
    layout->addWidget(plainTextLabel);

    //=============================================
    // 8. 边距和缩进 (margin, indent)
    //=============================================
    QLabel *marginIndentLabel = new QLabel("Text with margin and indent.");
    marginIndentLabel->setMargin(10); // 设置边距
    marginIndentLabel->setIndent(20); // 设置缩进
    marginIndentLabel->setStyleSheet("border: 1px solid green; background-color: lightgray;"); // 添加边框和背景以便观察效果
    layout->addWidget(marginIndentLabel);


    window.setWindowTitle("QLabel Properties Example");
    window.show();

    return app.exec();
}

效果:

1.3、常用方法 (设置文本、图像、清空等)

  • 设置文本:

    • 方法:setText(const QString &)

    • 描述:设置标签的文本内容,支持普通文本或 HTML。

    • 示例:label->setText("<b>Bold Text</b>");

  • 设置图像:

    • 方法:setPixmap(const QPixmap &)

    • 描述:设置标签显示的图像。

    • 示例:label->setPixmap(QPixmap(":/resources/image.png"));

  • 清空内容:

    • 方法:clear()

    • 描述:清除标签的文本或图像内容。

    • 示例:label->clear();

  • 设置对齐方式:

    • 方法:setAlignment(Qt::Alignment)

    • 描述:设置文本或图像的对齐方式。

    • 示例:label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

  • 设置伙伴控件:

    • 方法:setBuddy(QWidget *)

    • 描述:将标签与指定控件关联,用于快捷键导航。

    • 示例:label->setBuddy(lineEdit);

  • 设置超链接:

    • 方法:setOpenExternalLinks(bool)

    • 描述:启用后,点击 HTML 格式的超链接会自动打开外部浏览器。

    • 示例:label->setOpenExternalLinks(true);

  • 设置文本交互标志:

    • 方法:setTextInteractionFlags(Qt::TextInteractionFlags)

    • 描述:控制文本的交互行为,如是否可选择、可编辑等。

    • 示例:label->setTextInteractionFlags(Qt::TextSelectableByMouse);

#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPixmap>
#include <QLineEdit>
#include <QPushButton>
#include <QUrl>
#include <QDesktopServices>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QWidget window;
    QVBoxLayout *mainLayout = new QVBoxLayout(&window);

    //=====================================
    // --- 1. 设置文本 (setText) ---
    //=====================================
    QLabel *textLabel = new QLabel();
    textLabel->setText("Initial Text"); // 初始文本
    mainLayout->addWidget(textLabel);

    QPushButton *setTextButton = new QPushButton("Set Bold Text");
    // 连接按钮的 clicked 信号到 lambda 函数,设置标签文本为粗体 HTML
    QObject::connect(setTextButton, &QPushButton::clicked, [=]() {
        textLabel->setText("<b>Bold Text Set by Button</b>");
    });
    mainLayout->addWidget(setTextButton);

    //====================================
    // --- 2. 设置图像 (setPixmap) ---
    //=====================================
    QLabel *pixmapLabel = new QLabel();
    // 注意:这里使用资源文件路径 ":/resources/image.png"
    // 你需要在项目中设置资源文件 (.qrc) 并包含 image.png
    // 如果没有资源文件,请替换为实际图片文件路径,如 "image.png"
    QPixmap initialPixmap(":/resources/qt-logo.png"); // 假设你有一个名为 qt-logo.png 的资源
    if (!initialPixmap.isNull()) {
        pixmapLabel->setPixmap(initialPixmap.scaledToHeight(50, Qt::SmoothTransformation)); // 设置初始图像并缩放
        mainLayout->addWidget(pixmapLabel);
    } else {
         QLabel *pixmapErrorLabel = new QLabel("Pixmap resource ':/resources/qt-logo.png' not found or invalid!");
         mainLayout->addWidget(pixmapErrorLabel);
    }


    QPushButton *setNewPixmapButton = new QPushButton("Set Another Image");
     // 你可以准备另一张图片资源或文件
    QObject::connect(setNewPixmapButton, &QPushButton::clicked, [=]() {
        QPixmap newPixmap(":/resources/qt-project-logo.png"); // 另一张图片资源
         if (!newPixmap.isNull()) {
            pixmapLabel->setPixmap(newPixmap.scaledToHeight(50, Qt::SmoothTransformation));
         } else {
             // 处理图片未找到的情况
         }
    });
    mainLayout->addWidget(setNewPixmapButton);

    //===============================
    // --- 3. 清空内容 (clear) ---
    //===============================
    QLabel *clearableLabel = new QLabel("This text can be cleared.");
    mainLayout->addWidget(clearableLabel);

    QPushButton *clearButton = new QPushButton("Clear Label");
    QObject::connect(clearButton, &QPushButton::clicked, [=]() {
        clearableLabel->clear(); // 清空标签内容
    });
    mainLayout->addWidget(clearButton);

    //=============================================
    // --- 4. 设置对齐方式 (setAlignment) ---
    //=============================================
    QLabel *alignLabel = new QLabel("Align Me");
    alignLabel->setStyleSheet("border: 1px solid red;"); // 添加边框方便观察
    mainLayout->addWidget(alignLabel);

    QPushButton *alignButton = new QPushButton("Align Center");
    QObject::connect(alignButton, &QPushButton::clicked, [=]() {
        alignLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); // 水平垂直居中
    });
    mainLayout->addWidget(alignButton);

    //============================================
    // --- 5. 设置伙伴控件 (setBuddy) ---
    //============================================
    QLabel *buddyLabel = new QLabel("Address(&A):");
    QLineEdit *addressLineEdit = new QLineEdit();
    buddyLabel->setBuddy(addressLineEdit); // 将标签与 LineEdit 关联
    QHBoxLayout *buddyLayout = new QHBoxLayout();
    buddyLayout->addWidget(buddyLabel);
    buddyLayout->addWidget(addressLineEdit);
    mainLayout->addLayout(buddyLayout);

    //=====================================================
    // --- 6. 设置超链接 (setOpenExternalLinks) ---
    //=====================================================
    QLabel *linkLabel = new QLabel("<a href=\"https://www.qt.io\">Visit Qt Website</a>");
    linkLabel->setOpenExternalLinks(true); // 启用外部链接打开
    mainLayout->addWidget(linkLabel);

    //=====================================================================
    // --- 7. 设置文本交互标志 (setTextInteractionFlags) ---
    //=====================================================================
    QLabel *interactiveLabel = new QLabel("Selectable Text. You can copy this.");
    interactiveLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextBrowserInteraction); // 允许鼠标选择和浏览器式交互
    mainLayout->addWidget(interactiveLabel);


    window.setWindowTitle("QLabel Methods Example");
    window.show();

    return app.exec();
}

效果:

1.4、常用信号 (链接激活、自定义上下文菜单等)

  • 链接激活 (linkActivated):

    • 信号:void linkActivated(const QString &link)

    • 描述:当用户点击标签中的超链接(HTML 格式)时触发,传递链接的 URL。

  • 链接悬停 (linkHovered):

    • 信号:void linkHovered(const QString &link)

    • 描述:当鼠标悬停在超链接上时触发,传递悬停的 URL。

  • 自定义上下文菜单 (customContextMenuRequested):

    • 信号:void customContextMenuRequested(const QPoint &pos)

    • 描述:当用户右键点击标签时触发,可用于弹出自定义上下文菜单。

#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QUrl>
#include <QDesktopServices>
#include <QDebug>
#include <QPoint>
#include <QMenu>
#include <QAction>

// 为了演示 customContextMenuRequested 信号,我们创建一个简单的 Widget 类
class MyLabelWidget : public QWidget {
    Q_OBJECT

public:
    MyLabelWidget(QWidget *parent = nullptr) : QWidget(parent) {
        QVBoxLayout *layout = new QVBoxLayout(this);

        QLabel *interactiveLabel = new QLabel();
        // 设置支持富文本和超链接
        interactiveLabel->setTextFormat(Qt::RichText);
        interactiveLabel->setText("<a href=\"https://www.qt.io\">Visit Qt Website</a> | <a href=\"https://www.example.com\">Example Link</a>");
        interactiveLabel->setOpenExternalLinks(false); // 我们自己处理 linkActivated

        // 启用自定义上下文菜单
        interactiveLabel->setContextMenuPolicy(Qt::CustomContextMenu);


        // --- 连接信号 ---

        // 1. 链接激活 (linkActivated)
        connect(interactiveLabel, &QLabel::linkActivated, this, &MyLabelWidget::handleLinkActivated);

        // 2. 链接悬停 (linkHovered)
        connect(interactiveLabel, &QLabel::linkHovered, this, &MyLabelWidget::handleLinkHovered);

        // 3. 自定义上下文菜单 (customContextMenuRequested)
        connect(interactiveLabel, &QLabel::customContextMenuRequested, this, &MyLabelWidget::showCustomMenu);

        layout->addWidget(interactiveLabel);

        this->setWindowTitle("QLabel Signals Example");
    }

private slots:
    // 处理链接激活信号的槽
    void handleLinkActivated(const QString &link) {
        qDebug() << "Link Activated:" << link;
        // 使用 QDesktopServices 打开外部链接
        QDesktopServices::openUrl(QUrl(link));
    }

    // 处理链接悬停信号的槽
    void handleLinkHovered(const QString &link) {
        qDebug() << "Link Hovered:" << link;
        // 你可以在这里更新状态栏或执行其他操作
    }

    // 处理自定义上下文菜单请求的槽
    void showCustomMenu(const QPoint &pos) {
        qDebug() << "Custom Context Menu Requested at:" << pos;

        // 创建上下文菜单
        QMenu contextMenu(tr("Context Menu"), this);

        QAction *action1 = new QAction(tr("Action 1"), this);
        QAction *action2 = new QAction(tr("Action 2"), this);

        // 连接菜单项的 triggered 信号到槽
        connect(action1, &QAction::triggered, [](){ qDebug() << "Action 1 triggered!"; });
        connect(action2, &QAction::triggered, [](){ qDebug() << "Action 2 triggered!"; });

        // 将动作添加到菜单
        contextMenu.addAction(action1);
        contextMenu.addAction(action2);

        // 在全局位置显示菜单
        // pos 是相对于控件左上角的位置,mapToGlobal() 转换为屏幕全局位置
        contextMenu.exec(mapToGlobal(pos));
    }
};

#include "main.moc" // moc 文件通常在编译时生成

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    MyLabelWidget window;
    window.show();

    return app.exec();
}

效果:右击弹出选项按钮

1.6、样式表应用

QLabel 支持 Qt 样式表(QSS),可以自定义外观,如字体、颜色、背景、边框等。

  • 自定义文本样式:

    label->setStyleSheet("QLabel { color: blue; font-size: 16px; font-weight: bold; }");
    • 效果:文本变为蓝色,16像素大小,加粗。

  • 设置背景和边框:

    label->setStyleSheet("QLabel { background-color: #f0f0f0; border: 1px solid black; padding: 5px; }");
    • 效果:标签具有灰色背景、黑色边框和 5 像素内边距。

  • 超链接样式:

    label->setStyleSheet("QLabel { color: #0000FF; }"
                         "QLabel:hover { color: #FF0000; text-decoration: underline; }");
    • 效果:超链接默认蓝色,鼠标悬停时变红并加下划线。

  • 圆角图片标签:

    label->setStyleSheet("QLabel { border: 2px solid gray; border-radius: 10px; }");
    label->setPixmap(QPixmap("image.png"));
    • 效果:图片标签具有圆角边框。


待补充...

  • QPushButton:标准按钮,支持点击触发事件。

  • QToolButton:工具栏按钮,支持图标和菜单。

  • QCheckBox:复选框,支持选中/未选中状态。

  • QRadioButton:单选按钮,用于互斥选择。

  • QComboBox:下拉列表框,支持选择或编辑。

  • QLineEdit:单行文本输入框,支持验证和掩码。

  • QTextEdit:多行文本编辑器,支持富文本。

  • QPlainTextEdit:轻量级纯文本编辑器。

  • QSpinBox:整数输入框,带上下箭头。

  • QDoubleSpinBox:浮点数输入框。

  • QSlider:滑动条,用于选择数值范围。

  • QProgressBar:进度条,显示任务进度。

  • QDial:旋钮控件,用于调整数值。

  • QDateEdit、QTimeEdit、QDateTimeEdit:日期、时间或日期时间输入控件。

  • QCalendarWidget:日历控件,用于选择日期。

  • QGroupBox:分组框,用于组织控件。

  • QFrame:框架控件,支持边框和样式。

  • QTabWidget:选项卡控件,支持多页面切换。

  • QStackedWidget:堆叠控件,用于切换显示单个页面。

  • QToolBox:工具箱控件,类似折叠的选项卡。

二、高级控件(Advanced Widgets)

提供更复杂的功能,适合特定场景。

  • QListWidget:列表控件,支持多选和图标。

  • QTreeWidget:树形控件,显示分层数据。

  • QTableWidget:表格控件,支持单元格编辑。

  • QColumnView:列视图,适合分层数据浏览。

  • QDockWidget:可停靠窗口,支持浮动和拖动。

  • QMdiArea、QMdiSubWindow:多文档界面(MDI)区域和子窗口。

  • QTextBrowser:只读富文本浏览器,支持超链接。

  • QGraphicsView、QGraphicsScene:图形视图框架,用于2D图形和自定义场景(与Widgets结合使用)。

  • QOpenGLWidget:OpenGL渲染窗口,支持3D图形。

三、容器类(Containers)

用于组织和布局其他控件。

  • QWidget:所有控件的基类,提供基本窗口功能。

  • QMainWindow:主窗口类,提供菜单栏、工具栏和状态栏。

  • QDialog:对话框基类,支持模态和非模态。

  • QScrollArea:滚动区域,支持大型内容显示。

  • QSplitter:分割器,允许用户调整子控件大小。

  • QTabBar:选项卡栏,与QTabWidget配合使用。

四、布局管理(Layouts)

用于自动排列控件,适应窗口大小变化。

  • QHBoxLayout:水平布局。

  • QVBoxLayout:垂直布局。

  • QGridLayout:网格布局。

  • QFormLayout:表单布局,适合标签-输入对。

  • QStackedLayout:堆叠布局,显示单一控件。

  • QLayout:布局基类,提供通用布局功能。

五、菜单和工具栏(Menus and Toolbars)

用于创建应用程序的导航和交互功能。

  • QMenu:弹出菜单,支持子菜单和动作。

  • QMenuBar:菜单栏,位于主窗口顶部。

  • QToolBar:工具栏,支持可拖动和浮动。

  • QAction:动作抽象,表示菜单项、工具栏按钮等。

六、对话框(Dialogs)

预定义的对话框,用于常见任务。

  • QMessageBox:消息框,显示提示、警告或错误。

  • QInputDialog:输入对话框,获取用户输入。

  • QFileDialog:文件选择对话框。

  • QColorDialog:颜色选择对话框。

  • QFontDialog:字体选择对话框。

  • QProgressDialog:进度对话框,显示任务进度。

  • QErrorMessage:错误消息对话框,支持重复消息过滤。

七、事件和交互

支持用户交互和事件处理。

  • QEvent:事件基类,用于处理鼠标、键盘等事件。

  • QMouseEvent、QKeyEvent:鼠标和键盘事件。

  • QDrag、QDropEvent:拖放支持。

  • QGestureEvent:手势事件(如触摸设备)。

  • QActionEvent:动作触发事件。

八、样式和主题(Styles and Themes)

用于自定义控件外观。

  • QStyle:控件绘制基类,支持自定义样式。

  • QStyleFactory:创建平台特定样式(如Windows、Fusion)。

  • QStyleSheet:通过CSS-like语法自定义控件外观。

  • QPalette:颜色配置,用于控件主题。

九、其他功能

  • QApplication:应用程序类,管理全局设置和事件循环。

  • QClipboard:剪贴板操作,支持文本、图像等。

  • QDesktopWidget:访问屏幕信息(如分辨率)。

  • QSystemTrayIcon:系统托盘图标支持。

  • QStatusBar:状态栏,显示临时信息。

  • QWhatsThis:上下文帮助功能。

  • QToolTip:工具提示支持。

  • QAccessible:辅助功能支持,增强可访问性。

十、模型/视图支持

虽然主要由Qt Model/View模块处理,但Widgets中包含相关控件:

  • QListView、QTreeView、QTableView:基于模型的视图控件,与QAbstractItemModel配合使用。

十一、动画和效果

  • QPropertyAnimation:属性动画,用于控件动态效果。

  • QGraphicsEffect:图形效果,如阴影、模糊(与QGraphicsView结合)。

十二、国际化支持

  • QTranslator:支持界面多语言翻译。

  • QLocale:本地化支持,处理日期、数字格式等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旭唐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
OSZAR »