1. Introduction to QLabel
QLabel is a very basic and important class in the Qt library. It is mainly used to display text or pictures in a graphical user interface (GUI). The most common usage is to display a text or label on the window, such as "username", "password" and so on. QLabel inherits from QFrame, so it can have frames too. It handles rich text formatting, which means you can change the color, font, etc. of parts of the text. QLabel also supports interaction, for example, when it contains a web link, the link is clickable.
2. Common properties, methods and signals of QLabel
Attributes | describe |
---|---|
text | The text displayed on the QLabel |
pixmap | Image displayed on QLabel |
alignment | Alignment, such as Qt::AlignLeft, Qt::AlignRight, Qt::AlignCenter, etc. |
becomeWrap | Whether to enable automatic line wrapping |
method | describe |
---|---|
setText(const QString &text) | Set the text of the QLabel |
setPixmap(const QPixmap &pixmap) | Set the picture of QLabel |
clear() | Clear text and pictures on QLabel |
setAlignment(Qt::Alignment alignment) | set the alignment of the text |
setWordWrap(bool on) | Set whether to enable automatic line wrap |
Signal | describe |
---|---|
linkActivated(const QString &link) | Emitted when a link in the text is clicked |
linkHovered(const QString &link) | Emitted when the mouse is over a link in the text |
3. Example of using QLabel
- basic use
#include <QApplication>
#include <QLabel>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QLabel label("Hello, World!");
label.show();
return app.exec();
}
2. Set text alignment
#include <QApplication>
#include <QLabel>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QLabel label("Hello, World!");
label.setAlignment(Qt::AlignCenter);
label.show();
return app.exec();
}
- display image
#include <QApplication>
#include <QLabel>
#include <QPixmap>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QLabel label;
QPixmap pixmap("/path/to/your/image.png");
label.setPixmap(pixmap);
label.show();
return app.exec();
}
- link interaction
#include <QApplication>
#include <QLabel>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QLabel label("<a href='https://www.qt.io/'>Visit Qt Homepage</a>");
label.setOpenExternalLinks(true); // 打开外部链接
label.show();
return app.exec();
}
4. QLabelSummary
QLabel is a very basic and commonly used class, it can be conveniently used to display text or pictures, and can handle rich text and links. Proficiency in the use of QLabel is essential for Qt GUI development. I hope this tutorial is helpful to you, and if you have any other questions about Qt, please feel free to ask me.