Как изменить текст qlabel

QLabel используется для отображения текста или изображения.Функциональность взаимодействия с пользователем не предусмотрена.Визуальный вид метки может быть настроен различными способами,и она может быть использована для указания мнемонической клавиши фокуса для другого виджета.

QLabel используется для отображения текста или изображения.Функциональность взаимодействия с пользователем не предусмотрена.Визуальный вид метки может быть настроен различными способами,и она может быть использована для указания мнемонической клавиши фокуса для другого виджета.

Предупреждение: при передаче QString конструктору или вызове setText () убедитесь, что вводимые данные дезинфицированы, так как QLabel пытается угадать, отображает ли он текст как обычный текст или как расширенный текст, подмножество разметки HTML 4. Вы можете явно вызвать setTextFormat (), например, если вы ожидаете, что текст будет в простом формате, но не можете управлять источником текста (например, при отображении данных, загруженных из Интернета).

При изменении содержимого с помощью любой из этих функций любое предыдущее содержимое удаляется.

Позиционирование содержимого в области виджета QLabel можно настроить с помощью setAlignment () и setIndent (). Текстовое содержимое также может переносить строки вдоль границ слов с помощью setWordWrap (). Например, этот код устанавливает утопленную панель с двухстрочным текстом в правом нижнем углу (обе строки находятся на одном уровне с правой стороной этикетки):

Свойства и функции, которые QLabel наследует от QFrame, также можно использовать для указания фрейма виджета, который будет использоваться для любой данной метки.

QLabel часто используется как метка для интерактивного виджета. Для этого использования QLabel предоставляет полезный механизм для добавления мнемоники (см. QKeySequence ), которая установит фокус клавиатуры на другой виджет (называемый «приятелем» QLabel). Например:

В этом примере фокус клавиатуры передается партнеру метки ( QLineEdit ), когда пользователь нажимает Alt + P. Если партнером была кнопка (унаследованная от QAbstractButton ), запуск мнемоники имитировал бы нажатие кнопки.

Property Documentation

выравнивание : Qt::Выравнивание

Это свойство содержит выравнивание содержимого этикетки.

По умолчанию содержимое этикетки выровнено по левому краю и центрировано по вертикали.

Access functions:

Qt::Alignment alignment() const
void setAlignment(Qt::Alignment)

См. Также текст .

[read-only] hasSelectedText : const bool

Это свойство определяет,есть ли выделенный текст

hasSelectedText () возвращает true , если пользователь выделил часть или весь текст; в противном случае возвращает false .

По умолчанию это свойство имеет значение false .

Примечание . TextInteractionFlags , установленные на метке, должны включать либо TextSelectableByMouse, либо TextSelectableByKeyboard.

Access functions:

bool hasSelectedText() const

См. Также selectedText ().

абзац:int

Это свойство содержит отступ текста этикетки в пикселях.

Если метка отображает текст, отступ применяется к левому краю, если выравнивание () равно Qt::AlignLeft , к правому краю, если выравнивание () равно Qt::AlignRight , к верхнему краю, если выравнивание () равно Qt::AlignTop , и к нижнему краю, если выравнивание () равно Qt::AlignBottom .

Если отступ отрицателен или отступ не задан, метка вычисляет эффективный отступ следующим образом: Если frameWidth () равно 0, эффективный отступ становится равным 0. Если frameWidth () больше 0, эффективный отступ становится равным половине отступа. ширина символа «x» текущего шрифта виджета ().

По умолчанию отступом является -1,что означает,что эффективный отступ рассчитывается описанным выше способом.

Access functions:

int indent() const
void setIndent(int)

См. также выравнивание , поля , frameWidth () и font ().

маржа:int

Это свойство удерживает ширину поля

Поле-это расстояние между самым внутренним пикселем рамы и самым внешним пикселем содержимого.

Маржа по умолчанию равна 0.

Access functions:

int margin() const
void setMargin(int)

См. Также отступ .

openExternalLinks : bool

Указывает, должен ли QLabel автоматически открывать ссылки с помощью QDesktopServices::openUrl () вместо генерации сигнала linkActivated ().

Примечание . TextInteractionFlags , установленные на этикетке, должны включать LinksAccessibleByMouse или LinksAccessibleByKeyboard.

Значение по умолчанию равно false.

Access functions:

bool openExternalLinks() const
void setOpenExternalLinks(boolopen)

См. также textInteractionFlags ().

растровое изображение: QPixmap

Это свойство содержит пиксмап метки.

Установка растрового изображения очищает любое предыдущее содержимое.Ярлык «приятель»,если он есть,отключается.

Access functions:

QPixmap pixmap() const
void setPixmap(const QPixmap &)

scaledContents:шерсть

Это свойство определяет,будет ли этикетка масштабировать свое содержимое,чтобы заполнить все доступное пространство.

Когда эта функция включена и на этикетке отображается растровое изображение,оно будет масштабироваться,чтобы заполнить доступное пространство.

По умолчанию это свойство ложное.

Access functions:

bool hasScaledContents() const
void setScaledContents(bool)

[read-only] selectedText : const QString

Это свойство удерживает выделенный текст

При отсутствии выделенного текста значение этого свойства является пустой строкой.

По умолчанию это свойство содержит пустую строку.

Примечание . TextInteractionFlags , установленные на метке, должны включать либо TextSelectableByMouse, либо TextSelectableByKeyboard.

Access functions:

QString selectedText() const

См. Также hasSelectedText ().

текст: QString

Это свойство содержит текст этикетки

Если текст не установлен,то возвращается пустая строка.Установка текста очищает предыдущее содержимое.

Текст будет интерпретироваться либо как обычный текст, либо как форматированный текст, в зависимости от настройки формата текста; см. setTextFormat (). Значение по умолчанию — Qt::AutoText ; т.е. QLabel попытается автоматически определить формат набора текста. См. Поддерживаемое подмножество HTML для определения форматированного текста.

Если приятель установлен,мнемоническая клавиша приятеля обновляется из нового текста.

Обратите внимание, что QLabel хорошо подходит для отображения небольших документов с форматированным текстом, таких как небольшие документы, которые получают свои специфические для документа настройки (шрифт, цвет текста, цвет ссылки) из палитры меток и свойств шрифта. Для больших документов используйте вместо этого QTextEdit в режиме только для чтения. QTextEdit также может предоставить полосу прокрутки при необходимости.

Примечание. Эта функция включает отслеживание мыши, еслиtextсодержит богатый текст.

Access functions:

QString text() const
void setText (константа QString &)

См. также setTextFormat (), setBuddy () и выравнивание .

The QLabel widget provides a text or image display.
More…

#include <qlabel.h>

Public Slots

void  clear ()
  Clears any label contents. More…
 
void  setMovie (QMovie *movie)
  Sets the label contents to movie. More…
 
void  setNum (int)
  Sets the label contents to plain text containing the textual representation of integer num. More…
 
void  setNum (double)
  Sets the label contents to plain text containing the textual representation of double num. More…
 
void  setPicture (const QPicture &)
  Sets the label contents to picture. More…
 
void  setPixmap (const QPixmap &)
 
void  setText (const QString &)
 
- Public Slots inherited from QWidget
bool  close ()
  Closes this widget. More…
 
void  hide ()
  Hides the widget. More…
 
void  lower ()
  Lowers the widget to the bottom of the parent widget’s stack. More…
 
void  raise ()
  Raises this widget to the top of the parent widget’s stack. More…
 
void  repaint ()
  Repaints the widget directly by calling paintEvent() immediately, unless updates are disabled or the widget is hidden. More…
 
void  setDisabled (bool)
  Disables widget input events if disable is true; otherwise enables input events. More…
 
void  setEnabled (bool)
 
void  setFocus ()
  Gives the keyboard input focus to this widget (or its focus proxy) if this widget or one of its parents is the active window. More…
 
void  setHidden (bool hidden)
  Convenience function, equivalent to setVisible(!hidden). More…
 
QT_MOC_COMPAT void  setShown (bool shown)
  Use setVisible(shown) instead. More…
 
void  setStyleSheet (const QString &styleSheet)
 
virtual void  setVisible (bool visible)
 
void  setWindowModified (bool)
 
void  setWindowTitle (const QString &)
 
void  show ()
  Shows the widget and its child widgets. More…
 
void  showFullScreen ()
  Shows the widget in full-screen mode. More…
 
void  showMaximized ()
  Shows the widget maximized. More…
 
void  showMinimized ()
  Shows the widget minimized, as an icon. More…
 
void  showNormal ()
  Restores the widget after it has been maximized or minimized. More…
 
void  update ()
  Updates the widget unless updates are disabled or the widget is hidden. More…
 
- Public Slots inherited from QObject
void  deleteLater ()
  Schedules this object for deletion. More…
 

Signals

void  linkActivated (const QString &link)
  This signal is emitted when the user clicks a link. More…
 
void  linkHovered (const QString &link)
  This signal is emitted when the user hovers over a link. More…
 
- Signals inherited from QWidget
void  customContextMenuRequested (const QPoint &pos)
  This signal is emitted when the widget’s contextMenuPolicy is Qt::CustomContextMenu, and the user has requested a context menu on the widget. More…
 
- Signals inherited from QObject
void  destroyed (QObject *=0)
  This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More…
 

Public Functions

Qt::Alignment  alignment () const
 
QWidget *  buddy () const
  Returns this label’s buddy, or 0 if no buddy is currently set. More…
 
bool  hasScaledContents () const
 
bool  hasSelectedText () const
 
int  heightForWidth (int) const
  Reimplemented Function More…
 
int  indent () const
 
int  margin () const
 
QSize  minimumSizeHint () const
  Reimplemented Function More…
 
QMovie *  movie () const
  Returns a pointer to the label’s movie, or 0 if no movie has been set. More…
 
bool  openExternalLinks () const
 
const QPicture *  picture () const
  Returns the label’s picture or 0 if the label doesn’t have a picture. More…
 
const QPixmap *  pixmap () const
 
  QLabel (QWidget *parent=0, Qt::WindowFlags f=0)
  Constructs an empty label. More…
 
  QLabel (const QString &text, QWidget *parent=0, Qt::WindowFlags f=0)
  Constructs a label that displays the text, text. More…
 
QString  selectedText () const
 
int  selectionStart () const
  selectionStart() returns the index of the first selected character in the label or -1 if no text is selected. More…
 
void  setAlignment (Qt::Alignment)
  Without this function, a call to e. More…
 
void  setBuddy (QWidget *)
  Sets this label’s buddy to buddy. More…
 
void  setIndent (int)
 
void  setMargin (int)
 
void  setOpenExternalLinks (bool open)
 
void  setScaledContents (bool)
 
void  setSelection (int, int)
  Selects text from position start and for length characters. More…
 
void  setTextFormat (Qt::TextFormat)
 
void  setTextInteractionFlags (Qt::TextInteractionFlags flags)
 
void  setWordWrap (bool on)
 
QSize  sizeHint () const
  em>Reimplemented Function More…
 
QString  text () const
 
Qt::TextFormat  textFormat () const
 
Qt::TextInteractionFlags  textInteractionFlags () const
 
bool  wordWrap () const
 
  ~QLabel ()
  Destroys the label. More…
 
- Public Functions inherited from QFrame
QRect  frameRect () const
 
Shadow  frameShadow () const
 
Shape  frameShape () const
 
int  frameStyle () const
  Returns the frame style. More…
 
int  frameWidth () const
 
int  lineWidth () const
 
int  midLineWidth () const
 
  QFrame (QWidget *parent=0, Qt::WindowFlags f=0)
  Constructs a frame widget with frame style NoFrame and a 1-pixel frame width. More…
 
void  setFrameRect (const QRect &)
  em>Reimplemented Function More…
 
void  setFrameShadow (Shadow)
 
void  setFrameShape (Shape)
 
void  setFrameStyle (int)
  Sets the frame style to style. More…
 
void  setLineWidth (int)
 
void  setMidLineWidth (int)
 
  ~QFrame ()
  Destroys the frame. More…
 
- Public Functions inherited from QWidget
bool  acceptDrops () const
 
QString  accessibleDescription () const
 
QString  accessibleName () const
 
QList< QAction * >  actions () const
  Returns the (possibly empty) list of this widget’s actions. More…
 
void  activateWindow ()
  Sets the top-level widget containing this widget to be the active window. More…
 
void  addAction (QAction *action)
  Appends the action action to this widget’s list of actions. More…
 
void  addActions (QList< QAction *> actions)
  Appends the actions actions to this widget’s list of actions. More…
 
void  adjustSize ()
  Adjusts the size of the widget to fit its contents. More…
 
bool  autoFillBackground () const
 
QPalette::ColorRole  backgroundRole () const
  Returns the background role of the widget. More…
 
QSize  baseSize () const
 
QWidget *  childAt (int x, int y) const
  Returns the visible child widget at the position ({x}, {y}) in the widget’s coordinate system. More…
 
QWidget *  childAt (const QPoint &p) const
  Returns the visible child widget at point p in the widget’s own coordinate system. More…
 
QRect  childrenRect () const
 
QRegion  childrenRegion () const
 
void  clearFocus ()
  Takes keyboard input focus from the widget. More…
 
void  clearMask ()
  Removes any mask set by setMask(). More…
 
QMargins  contentsMargins () const
  The contentsMargins function returns the widget’s contents margins. More…
 
QRect  contentsRect () const
  Returns the area inside the widget’s margins. More…
 
Qt::ContextMenuPolicy  contextMenuPolicy () const
 
void  createWinId ()
 
QCursor  cursor () const
 
int  devType () const
 
WId  effectiveWinId () const
  Returns the effective window system identifier of the widget, i. More…
 
void  ensurePolished () const
  Ensures that the widget has been polished by QStyle (i.e., has a proper font and palette). More…
 
Qt::FocusPolicy  focusPolicy () const
 
QWidget *  focusProxy () const
  Returns the focus proxy, or 0 if there is no focus proxy. More…
 
QWidget *  focusWidget () const
  Returns the last child of this widget that setFocus had been called on. More…
 
const QFont &  font () const
 
QFontInfo  fontInfo () const
  Returns the font info for the widget’s current font. More…
 
QFontMetrics  fontMetrics () const
  Returns the font metrics for the widget’s current font. More…
 
QPalette::ColorRole  foregroundRole () const
  Returns the foreground role. More…
 
QRect  frameGeometry () const
 
QSize  frameSize () const
 
const QRect &  geometry () const
 
void  getContentsMargins (int *left, int *top, int *right, int *bottom) const
  Returns the widget’s contents margins for left, top, right, and bottom. More…
 
HDC  getDC () const
  Returns the window system handle of the widget, for low-level access. More…
 
void  grabGesture (Qt::GestureType type, Qt::GestureFlags flags=Qt::GestureFlags())
  Subscribes the widget to a given gesture with specific flags. More…
 
void  grabKeyboard ()
  Grabs the keyboard input. More…
 
void  grabMouse ()
  Grabs the mouse input. More…
 
void  grabMouse (const QCursor &)
 
int  grabShortcut (const QKeySequence &key, Qt::ShortcutContext context=Qt::WindowShortcut)
  Adds a shortcut to Qt’s shortcut system that watches for the given key sequence in the given context. More…
 
QGraphicsEffect *  graphicsEffect () const
  The graphicsEffect function returns a pointer to the widget’s graphics effect. More…
 
QGraphicsProxyWidget *  graphicsProxyWidget () const
  Returns the proxy widget for the corresponding embedded widget in a graphics view; otherwise returns 0. More…
 
bool  hasFocus () const
 
bool  hasMouseTracking () const
 
int  height () const
 
QInputContext *  inputContext ()
  This function returns the QInputContext for this widget. More…
 
Qt::InputMethodHints  inputMethodHints () const
 
virtual QVariant  inputMethodQuery (Qt::InputMethodQuery) const
  This method is only relevant for input widgets. More…
 
void  insertAction (QAction *before, QAction *action)
  Inserts the action action to this widget’s list of actions, before the action before. More…
 
void  insertActions (QAction *before, QList< QAction *> actions)
  Inserts the actions actions to this widget’s list of actions, before the action before. More…
 
WId  internalWinId () const
  Returns the window system identifier of the widget, or 0 if the widget is not created yet. More…
 
bool  isActiveWindow () const
 
bool  isAncestorOf (const QWidget *child) const
  Returns true if this widget is a parent, (or grandparent and so on to any level), of the given child, and both widgets are within the same window; otherwise returns false. More…
 
bool  isEnabled () const
 
bool  isEnabledTo (QWidget *) const
  Returns true if this widget would become enabled if ancestor is enabled; otherwise returns false. More…
 
bool  isEnabledToTLW () const
  This function is deprecated. More…
 
bool  isFullScreen () const
 
bool  isHidden () const
  Returns true if the widget is hidden, otherwise returns false. More…
 
bool  isLeftToRight () const
 
bool  isMaximized () const
 
bool  isMinimized () const
 
bool  isModal () const
 
bool  isRightToLeft () const
 
bool  isTopLevel () const
  Use isWindow() instead. More…
 
bool  isVisible () const
 
bool  isVisibleTo (QWidget *) const
  Returns true if this widget would become visible if ancestor is shown; otherwise returns false. More…
 
bool  isWindow () const
  Returns true if the widget is an independent window, otherwise returns false. More…
 
bool  isWindowModified () const
 
QLayout *  layout () const
  Returns the layout manager that is installed on this widget, or 0 if no layout manager is installed. More…
 
Qt::LayoutDirection  layoutDirection () const
 
QLocale  locale () const
 
Qt::HANDLE  macCGHandle () const
  Returns the CoreGraphics handle of the widget. More…
 
Qt::HANDLE  macQDHandle () const
  Returns the QuickDraw handle of the widget. More…
 
QPoint  mapFrom (QWidget *, const QPoint &) const
  Translates the widget coordinate pos from the coordinate system of parent to this widget’s coordinate system. More…
 
QPoint  mapFromGlobal (const QPoint &) const
  Translates the global screen coordinate pos to widget coordinates. More…
 
QPoint  mapFromParent (const QPoint &) const
  Translates the parent widget coordinate pos to widget coordinates. More…
 
QPoint  mapTo (QWidget *, const QPoint &) const
  Translates the widget coordinate pos to the coordinate system of parent. More…
 
QPoint  mapToGlobal (const QPoint &) const
  Translates the widget coordinate pos to global screen coordinates. More…
 
QPoint  mapToParent (const QPoint &) const
  Translates the widget coordinate pos to a coordinate in the parent widget. More…
 
QRegion  mask () const
  Returns the mask currently set on a widget. More…
 
int  maximumHeight () const
 
QSize  maximumSize () const
 
int  maximumWidth () const
 
int  minimumHeight () const
 
QSize  minimumSize () const
 
int  minimumWidth () const
 
void  move (int x, int y)
  This corresponds to move(QPoint(x, y)). More…
 
void  move (const QPoint &)
 
QWidget *  nativeParentWidget () const
  Returns the native parent for this widget, i. More…
 
QWidget *  nextInFocusChain () const
  Returns the next widget in this widget’s focus chain. More…
 
QRect  normalGeometry () const
 
void  overrideWindowFlags (Qt::WindowFlags type)
  Sets the window flags for the widget to flags, without telling the window system. More…
 
void  overrideWindowState (Qt::WindowStates state)
 
QPaintEngine *  paintEngine () const
  Returns the widget’s paint engine. More…
 
const QPalette &  palette () const
 
QWidget *  parentWidget () const
  Returns the parent of this widget, or 0 if it does not have any parent widget. More…
 
QPoint  pos () const
 
QWidget *  previousInFocusChain () const
  The previousInFocusChain function returns the previous widget in this widget’s focus chain. More…
 
  QWidget (QWidget *parent=0, Qt::WindowFlags f=0)
  Constructs a widget which is a child of parent, with widget flags set to f. More…
 
QRect  rect () const
 
void  releaseDC (HDC) const
  Releases the HDC hdc acquired by a previous call to getDC(). More…
 
void  releaseKeyboard ()
  Releases the keyboard grab. More…
 
void  releaseMouse ()
  Releases the mouse grab. More…
 
void  releaseShortcut (int id)
  Removes the shortcut with the given id from Qt’s shortcut system. More…
 
void  removeAction (QAction *action)
  Removes the action action from this widget’s list of actions. More…
 
void  render (QPaintDevice *target, const QPoint &targetOffset=QPoint(), const QRegion &sourceRegion=QRegion(), RenderFlags renderFlags=RenderFlags(DrawWindowBackground|DrawChildren))
  Renders the sourceRegion of this widget into the target using renderFlags to determine how to render. More…
 
void  render (QPainter *painter, const QPoint &targetOffset=QPoint(), const QRegion &sourceRegion=QRegion(), RenderFlags renderFlags=RenderFlags(DrawWindowBackground|DrawChildren))
  Renders the widget into the painter’s QPainter::device(). More…
 
void  repaint (int x, int y, int w, int h)
  This version repaints a rectangle (x, y, w, h) inside the widget. More…
 
void  repaint (const QRect &)
  This version repaints a rectangle rect inside the widget. More…
 
void  repaint (const QRegion &)
  This version repaints a region rgn inside the widget. More…
 
void  resize (int w, int h)
  This corresponds to resize(QSize(w, h)). More…
 
void  resize (const QSize &)
 
bool  restoreGeometry (const QByteArray &geometry)
  Restores the geometry and state top-level widgets stored in the byte array geometry. More…
 
QByteArray  saveGeometry () const
  Saves the current geometry and state for top-level widgets. More…
 
void  scroll (int dx, int dy)
  Scrolls the widget including its children dx pixels to the right and dy downward. More…
 
void  scroll (int dx, int dy, const QRect &)
  This version only scrolls r and does not move the children of the widget. More…
 
void  setAcceptDrops (bool on)
 
void  setAccessibleDescription (const QString &description)
 
void  setAccessibleName (const QString &name)
 
void  setAttribute (Qt::WidgetAttribute, bool on=true)
  Sets the attribute attribute on this widget if on is true; otherwise clears the attribute. More…
 
void  setAutoFillBackground (bool enabled)
 
void  setBackgroundRole (QPalette::ColorRole)
  Sets the background role of the widget to role. More…
 
void  setBaseSize (const QSize &)
 
void  setBaseSize (int basew, int baseh)
  This corresponds to setBaseSize(QSize(basew, baseh)). More…
 
void  setContentsMargins (int left, int top, int right, int bottom)
  Sets the margins around the contents of the widget to have the sizes left, top, right, and bottom. More…
 
void  setContentsMargins (const QMargins &margins)
  The setContentsMargins function sets the margins around the widget’s contents. More…
 
void  setContextMenuPolicy (Qt::ContextMenuPolicy policy)
 
void  setCursor (const QCursor &)
 
void  setFixedHeight (int h)
  Sets both the minimum and maximum heights of the widget to h without changing the widths. More…
 
void  setFixedSize (const QSize &)
  Sets both the minimum and maximum sizes of the widget to s, thereby preventing it from ever growing or shrinking. More…
 
void  setFixedSize (int w, int h)
  Sets the width of the widget to w and the height to h. More…
 
void  setFixedWidth (int w)
  Sets both the minimum and maximum width of the widget to w without changing the heights. More…
 
void  setFocus (Qt::FocusReason reason)
  Gives the keyboard input focus to this widget (or its focus proxy) if this widget or one of its parents is the active window. More…
 
void  setFocusPolicy (Qt::FocusPolicy policy)
 
void  setFocusProxy (QWidget *)
  Sets the widget’s focus proxy to widget w. More…
 
void  setFont (const QFont &)
  Use the single-argument overload instead. More…
 
void  setForegroundRole (QPalette::ColorRole)
  Sets the foreground role of the widget to role. More…
 
void  setGeometry (int x, int y, int w, int h)
  This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.This corresponds to setGeometry(QRect(x, y, w, h)). More…
 
void  setGeometry (const QRect &)
 
void  setGraphicsEffect (QGraphicsEffect *effect)
  The setGraphicsEffect function is for setting the widget’s graphics effect. More…
 
void  setInputContext (QInputContext *)
  This function sets the input context context on this widget. More…
 
void  setInputMethodHints (Qt::InputMethodHints hints)
 
void  setLayout (QLayout *)
  Sets the layout manager for this widget to layout. More…
 
void  setLayoutDirection (Qt::LayoutDirection direction)
 
void  setLocale (const QLocale &locale)
 
void  setMask (const QBitmap &)
  Causes only the pixels of the widget for which bitmap has a corresponding 1 bit to be visible. More…
 
void  setMask (const QRegion &)
  Causes only the parts of the widget which overlap region to be visible. More…
 
void  setMaximumHeight (int maxh)
 
void  setMaximumSize (const QSize &)
 
void  setMaximumSize (int maxw, int maxh)
  This function corresponds to setMaximumSize(QSize(maxw, maxh)). More…
 
void  setMaximumWidth (int maxw)
 
void  setMinimumHeight (int minh)
 
void  setMinimumSize (const QSize &)
 
void  setMinimumSize (int minw, int minh)
  This function corresponds to setMinimumSize(QSize(minw, minh)). More…
 
void  setMinimumWidth (int minw)
 
void  setMouseTracking (bool enable)
 
void  setPalette (const QPalette &)
  Use the single-argument overload instead. More…
 
void  setParent (QWidget *parent)
  Sets the parent of the widget to parent, and resets the window flags. More…
 
void  setParent (QWidget *parent, Qt::WindowFlags f)
  This function also takes widget flags, f as an argument. More…
 
void  setShortcutAutoRepeat (int id, bool enable=true)
  If enable is true, auto repeat of the shortcut with the given id is enabled; otherwise it is disabled. More…
 
void  setShortcutEnabled (int id, bool enable=true)
  If enable is true, the shortcut with the given id is enabled; otherwise the shortcut is disabled. More…
 
void  setSizeIncrement (const QSize &)
 
void  setSizeIncrement (int w, int h)
  Sets the x (width) size increment to w and the y (height) size increment to h. More…
 
void  setSizePolicy (QSizePolicy)
 
void  setSizePolicy (QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
  Sets the size policy of the widget to horizontal and vertical, with standard stretch and no height-for-width. More…
 
void  setStatusTip (const QString &)
 
void  setStyle (QStyle *)
  Sets the widget’s GUI style to style. More…
 
void  setToolTip (const QString &)
 
void  setUpdatesEnabled (bool enable)
 
void  setupUi (QWidget *widget)
  Sets up the user interface for the specified widget. More…
 
void  setWhatsThis (const QString &)
 
void  setWindowFilePath (const QString &filePath)
 
void  setWindowFlags (Qt::WindowFlags type)
 
void  setWindowIcon (const QIcon &icon)
 
void  setWindowIconText (const QString &)
 
void  setWindowModality (Qt::WindowModality windowModality)
 
void  setWindowOpacity (qreal level)
 
void  setWindowRole (const QString &)
  Sets the window’s role to role. More…
 
void  setWindowState (Qt::WindowStates state)
  Sets the window state to windowState. More…
 
void  setWindowSurface (QWindowSurface *surface)
  Sets the window surface to be the surface specified. More…
 
QSize  size () const
 
QSize  sizeIncrement () const
 
QSizePolicy  sizePolicy () const
 
void  stackUnder (QWidget *)
  Places the widget under w in the parent widget’s stack. More…
 
QString  statusTip () const
 
QStyle *  style () const
 
QString  styleSheet () const
 
bool  testAttribute (Qt::WidgetAttribute) const
  Returns true if attribute attribute is set on this widget; otherwise returns false. More…
 
QString  toolTip () const
 
QWidget *  topLevelWidget () const
 
bool  underMouse () const
  Returns true if the widget is under the mouse cursor; otherwise returns false. More…
 
void  ungrabGesture (Qt::GestureType type)
  Unsubscribes the widget from a given gesture type. More…
 
void  unsetCursor ()
 
void  unsetLayoutDirection ()
 
void  unsetLocale ()
 
void  update (int x, int y, int w, int h)
  This version updates a rectangle (x, y, w, h) inside the widget. More…
 
void  update (const QRect &)
  This version updates a rectangle rect inside the widget. More…
 
void  update (const QRegion &)
  This version repaints a region rgn inside the widget. More…
 
void  updateGeometry ()
  Notifies the layout system that this widget has changed and may need to change geometry. More…
 
bool  updatesEnabled () const
 
QRegion  visibleRegion () const
  Returns the unobscured region where paint events can occur. More…
 
QString  whatsThis () const
 
int  width () const
 
QWidget *  window () const
  Returns the window for this widget, i.e. More…
 
QString  windowFilePath () const
 
Qt::WindowFlags  windowFlags () const
  Window flags are a combination of a type (e. More…
 
QIcon  windowIcon () const
 
QString  windowIconText () const
 
Qt::WindowModality  windowModality () const
 
qreal  windowOpacity () const
 
QString  windowRole () const
  Returns the window’s role, or an empty string. More…
 
Qt::WindowStates  windowState () const
  Returns the current window state. More…
 
QWindowSurface *  windowSurface () const
  Returns the QWindowSurface this widget will be drawn into. More…
 
QString  windowTitle () const
 
Qt::WindowType  windowType () const
  Returns the window type of this widget. More…
 
WId  winId () const
  Returns the window system identifier of the widget. More…
 
int  x () const
 
const QX11Info &  x11Info () const
  Returns information about the configuration of the X display used to display the widget. More…
 
Qt::HANDLE  x11PictureHandle () const
  Returns the X11 Picture handle of the widget for XRender support. More…
 
int  y () const
 
  ~QWidget ()
  Destroys the widget. More…
 
- Public Functions inherited from QObject
bool  blockSignals (bool b)
  If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More…
 
const QObjectList &  children () const
  Returns a list of child objects. More…
 
bool  connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool  disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool  disconnect (const QObject *receiver, const char *member=0)
 
void  dumpObjectInfo ()
  Dumps information about signal connections, etc. More…
 
void  dumpObjectTree ()
  Dumps a tree of children to the debug output. More…
 
QList< QByteArray >  dynamicPropertyNames () const
  Returns the names of all properties that were dynamically added to the object using setProperty(). More…
 
virtual bool  eventFilter (QObject *, QEvent *)
  Filters events if this object has been installed as an event filter for the watched object. More…
 
template<typename T >
findChild (const QString &aName=QString()) const
  Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More…
 
template<typename T >
QList< T >  findChildren (const QString &aName=QString()) const
  Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More…
 
template<typename T >
QList< T >  findChildren (const QRegExp &re) const
 
bool  inherits (const char *classname) const
  Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More…
 
void  installEventFilter (QObject *)
  Installs an event filter filterObj on this object. More…
 
bool  isWidgetType () const
  Returns true if the object is a widget; otherwise returns false. More…
 
void  killTimer (int id)
  Kills the timer with timer identifier, id. More…
 
virtual const QMetaObject *  metaObject () const
  Returns a pointer to the meta-object of this object. More…
 
void  moveToThread (QThread *thread)
  Changes the thread affinity for this object and its children. More…
 
QString  objectName () const
 
QObject *  parent () const
  Returns a pointer to the parent object. More…
 
QVariant  property (const char *name) const
  Returns the value of the object’s name property. More…
 
Q_INVOKABLE  QObject (QObject *parent=0)
  Constructs an object with parent object parent. More…
 
void  removeEventFilter (QObject *)
  Removes an event filter object obj from this object. More…
 
void  setObjectName (const QString &name)
 
void  setParent (QObject *)
  Makes the object a child of parent. More…
 
bool  setProperty (const char *name, const QVariant &value)
  Sets the value of the object’s name property to value. More…
 
void  setUserData (uint id, QObjectUserData *data)
 
bool  signalsBlocked () const
  Returns true if signals are blocked; otherwise returns false. More…
 
int  startTimer (int interval)
  Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More…
 
QThread *  thread () const
  Returns the thread in which the object lives. More…
 
QObjectUserData *  userData (uint id) const
 
virtual  ~QObject ()
  Destroys the object, deleting all its child objects. More…
 
- Public Functions inherited from QPaintDevice
int  colorCount () const
 
int  depth () const
 
int  height () const
 
int  heightMM () const
 
int  logicalDpiX () const
 
int  logicalDpiY () const
 
QT_DEPRECATED int  numColors () const
 
bool  paintingActive () const
 
int  physicalDpiX () const
 
int  physicalDpiY () const
 
int  width () const
 
int  widthMM () const
 
virtual  ~QPaintDevice ()
 

Protected Functions

void  changeEvent (QEvent *)
  Reimplemented Function More…
 
void  contextMenuEvent (QContextMenuEvent *ev)
  This event handler, for event event, can be reimplemented in a subclass to receive widget context menu events. More…
 
bool  event (QEvent *e)
  em>Reimplemented Function More…
 
void  focusInEvent (QFocusEvent *ev)
  Reimplemented Function More…
 
bool  focusNextPrevChild (bool next)
  em>Reimplemented Function More…
 
void  focusOutEvent (QFocusEvent *ev)
  Reimplemented Function More…
 
void  keyPressEvent (QKeyEvent *ev)
  em>Reimplemented Function More…
 
void  mouseMoveEvent (QMouseEvent *ev)
  em>Reimplemented Function More…
 
void  mousePressEvent (QMouseEvent *ev)
  em>Reimplemented Function More…
 
void  mouseReleaseEvent (QMouseEvent *ev)
  em>Reimplemented Function More…
 
void  paintEvent (QPaintEvent *)
  This event handler can be reimplemented in a subclass to receive paint events passed in event. More…
 
- Protected Functions inherited from QFrame
void  drawFrame (QPainter *)
  em>Reimplemented Function More…
 
  QFrame (QFramePrivate &dd, QWidget *parent=0, Qt::WindowFlags f=0)
 
- Protected Functions inherited from QWidget
virtual void  actionEvent (QActionEvent *)
  This event handler is called with the given event whenever the widget’s actions are changed. More…
 
virtual void  closeEvent (QCloseEvent *)
  This event handler is called with the given event when Qt receives a window close request for a top-level widget from the window system. More…
 
void  create (WId=0, bool initializeWindow=true, bool destroyOldWindow=true)
  Creates a new widget window if window is 0, otherwise sets the widget’s window to window. More…
 
void  destroy (bool destroyWindow=true, bool destroySubWindows=true)
  Frees up window system resources. More…
 
virtual void  dragEnterEvent (QDragEnterEvent *)
  This event handler is called when a drag is in progress and the mouse enters this widget. More…
 
virtual void  dragLeaveEvent (QDragLeaveEvent *)
  This event handler is called when a drag is in progress and the mouse leaves this widget. More…
 
virtual void  dragMoveEvent (QDragMoveEvent *)
  This event handler is called if a drag is in progress, and when any of the following conditions occur: the cursor enters this widget, the cursor moves within this widget, or a modifier key is pressed on the keyboard while this widget has the focus. More…
 
virtual void  dropEvent (QDropEvent *)
  This event handler is called when the drag is dropped on this widget. More…
 
virtual void  enabledChange (bool)
 
virtual void  enterEvent (QEvent *)
  This event handler can be reimplemented in a subclass to receive widget enter events which are passed in the event parameter. More…
 
bool  focusNextChild ()
  Finds a new widget to give the keyboard focus to, as appropriate for Tab, and returns true if it can find a new widget, or false if it can’t. More…
 
bool  focusPreviousChild ()
  Finds a new widget to give the keyboard focus to, as appropriate for Shift+Tab, and returns true if it can find a new widget, or false if it can’t. More…
 
virtual void  fontChange (const QFont &)
 
virtual void  hideEvent (QHideEvent *)
  This event handler can be reimplemented in a subclass to receive widget hide events. More…
 
virtual void  inputMethodEvent (QInputMethodEvent *)
  This event handler, for event event, can be reimplemented in a subclass to receive Input Method composition events. More…
 
virtual void  keyReleaseEvent (QKeyEvent *)
  This event handler, for event event, can be reimplemented in a subclass to receive key release events for the widget. More…
 
virtual void  languageChange ()
 
virtual void  leaveEvent (QEvent *)
  This event handler can be reimplemented in a subclass to receive widget leave events which are passed in the event parameter. More…
 
virtual bool  macEvent (EventHandlerCallRef, EventRef)
  This special event handler can be reimplemented in a subclass to receive native Macintosh events. More…
 
int  metric (PaintDeviceMetric) const
  Internal implementation of the virtual QPaintDevice::metric() function. More…
 
virtual void  mouseDoubleClickEvent (QMouseEvent *)
  This event handler, for event event, can be reimplemented in a subclass to receive mouse double click events for the widget. More…
 
virtual void  moveEvent (QMoveEvent *)
  This event handler can be reimplemented in a subclass to receive widget move events which are passed in the event parameter. More…
 
virtual void  paletteChange (const QPalette &)
 
  QWidget (QWidgetPrivate &d, QWidget *parent, Qt::WindowFlags f)
 
virtual bool  qwsEvent (QWSEvent *)
  This special event handler can be reimplemented in a subclass to receive native Qt for Embedded Linux events which are passed in the event parameter. More…
 
void  resetInputContext ()
  This function can be called on the widget that currently has focus to reset the input method operating on it. More…
 
virtual void  resizeEvent (QResizeEvent *)
  This event handler can be reimplemented in a subclass to receive widget resize events which are passed in the event parameter. More…
 
virtual void  showEvent (QShowEvent *)
  This event handler can be reimplemented in a subclass to receive widget show events which are passed in the event parameter. More…
 
virtual void  styleChange (QStyle &)
 
virtual void  tabletEvent (QTabletEvent *)
  This event handler, for event event, can be reimplemented in a subclass to receive tablet events for the widget. More…
 
virtual void  wheelEvent (QWheelEvent *)
  This event handler, for event event, can be reimplemented in a subclass to receive wheel events for the widget. More…
 
virtual void  windowActivationChange (bool)
 
virtual bool  winEvent (MSG *message, long *result)
  This special event handler can be reimplemented in a subclass to receive native Windows events which are passed in the message parameter. More…
 
virtual bool  x11Event (XEvent *)
  This special event handler can be reimplemented in a subclass to receive native X11 events passed in the event parameter. More…
 
- Protected Functions inherited from QObject
virtual void  childEvent (QChildEvent *)
  This event handler can be reimplemented in a subclass to receive child events. More…
 
virtual void  connectNotify (const char *signal)
  This virtual function is called when something has been connected to signal in this object. More…
 
virtual void  customEvent (QEvent *)
  This event handler can be reimplemented in a subclass to receive custom events. More…
 
virtual void  disconnectNotify (const char *signal)
  This virtual function is called when something has been disconnected from signal in this object. More…
 
  QObject (QObjectPrivate &dd, QObject *parent=0)
 
int  receivers (const char *signal) const
  Returns the number of receivers connected to the signal. More…
 
QObject *  sender () const
  Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More…
 
int  senderSignalIndex () const
 
virtual void  timerEvent (QTimerEvent *)
  This event handler can be reimplemented in a subclass to receive timer events for the object. More…
 
- Protected Functions inherited from QPaintDevice
  QPaintDevice ()
 

Properties

Qt::Alignment  alignment
  the alignment of the label’s contents More…
 
bool  hasSelectedText
  whether there is any text selected More…
 
int  indent
  the label’s text indent in pixels More…
 
int  margin
  the width of the margin More…
 
bool  openExternalLinks
  Specifies whether QLabel should automatically open links using QDesktopServices::openUrl() instead of emitting the linkActivated() signal. More…
 
QPixmap  pixmap
  the label’s pixmap More…
 
bool  scaledContents
  whether the label will scale its contents to fill all available space. More…
 
QString  selectedText
  the selected text More…
 
QString  text
  the label’s text More…
 
Qt::TextFormat  textFormat
  the label’s text format More…
 
Qt::TextInteractionFlags  textInteractionFlags
  Specifies how the label should interact with user input if it displays text. More…
 
bool  wordWrap
  the label’s word-wrapping policy More…
 

Friends

class  QBalloonTip
 
class  QMessageBoxPrivate
 
class  QTipLabel
 

Additional Inherited Members

- Public Types inherited from QFrame
enum   Shadow { Plain = 0x0010,
Raised = 0x0020,
Sunken = 0x0030
}
  This enum type defines the types of shadow that are used to give a 3D effect to frames. More…
 
enum   Shape {
  NoFrame = 0,
Box = 0x0001,
Panel = 0x0002,
WinPanel = 0x0003,

  HLine = 0x0004,
VLine = 0x0005,
StyledPanel = 0x0006

}
  This enum type defines the shapes of frame available. More…
 
enum   StyleMask { Shadow_Mask = 0x00f0,
Shape_Mask = 0x000f
}
  This enum defines two constants that can be used to extract the two components of frameStyle(): More…
 
- Public Types inherited from QWidget
enum   RenderFlag { DrawWindowBackground = 0x1,
DrawChildren = 0x2,
IgnoreMask = 0x4
}
  This enum describes how to render the widget when calling QWidget::render(). More…
 
- Public Types inherited from QPaintDevice
enum   PaintDeviceMetric {
  PdmWidth = 1,
PdmHeight,
PdmWidthMM,
PdmHeightMM,

  PdmNumColors,
PdmDepth,
PdmDpiX,
PdmDpiY,

  PdmPhysicalDpiX,
PdmPhysicalDpiY

}
 
- Static Public Functions inherited from QWidget
static QWidget *  find (WId)
  Returns a pointer to the widget with window identifer/handle id. More…
 
static QWidget *  keyboardGrabber ()
  Returns the widget that is currently grabbing the keyboard input. More…
 
static QWidget *  mouseGrabber ()
  Returns the widget that is currently grabbing the mouse input. More…
 
static void  setTabOrder (QWidget *, QWidget *)
  Puts the second widget after the first widget in the focus order. More…
 
- Static Public Functions inherited from QObject
static bool  connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
  Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More…
 
static bool  connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool  disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
  Disconnects signal in object sender from method in object receiver. More…
 
static bool  disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint  registerUserData ()
 
static QString  tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString  trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Functions inherited from QPaintDevice
static QWSDisplay *  qwsDisplay ()
 
- Static Public Variables inherited from QObject
static const QMetaObject  staticMetaObject
  This variable stores the meta-object for the class. More…
 
- Protected Slots inherited from QWidget
void  updateMicroFocus ()
  Updates the widget’s micro focus. More…
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectData >  d_ptr
 
- Protected Variables inherited from QPaintDevice
ushort  painters
 
- Static Protected Variables inherited from QObject
static const QMetaObject  staticQtMetaObject
 
- Related Functions inherited from QWidget
  QWidgetList
 
  WId
  Platform dependent window identifier. More…
 
- Related Functions inherited from QObject
qFindChildqFindChildren (const QObject *obj, const QString &name)()
 
QList< T >  qFindChildrenqFindChildren (const QObject *obj, const QString &name)()
 
QList< T >  qFindChildrenqFindChildren (const QObject *obj, const QRegExp &regExp)()
 
T *  qobject_cast (QObject *object)
 
  QObjectList
 
void *  qt_find_obj_child (QObject *parent, const char *type, const QString &name)
  Returns a pointer to the object named name that inherits type and with a given parent. More…
 
- Related Functions inherited from QPaintDevice
const Q_GUI_EXPORT QX11Info *  qt_x11Info (const QPaintDevice *pd)
  Returns the QX11Info structure for the pd paint device. More…
 

The QLabel widget provides a text or image display.

QLabel is used for displaying text or an image. No user interaction functionality is provided. The visual appearance of the label can be configured in various ways, and it can be used for specifying a focus mnemonic key for another widget.

A QLabel can contain any of the following content types:

Content Setting
Plain text Pass a QString to setText().
Rich text Pass a QString that contains rich text to setText().
A pixmap Pass a QPixmap to setPixmap().
A movie Pass a QMovie to setMovie().
A number Pass an int or a double to setNum(), which converts the number to plain text.
Nothing The same as an empty plain text. This is the default. Set by clear().
Warning
When passing a QString to the constructor or calling setText(), make sure to sanitize your input, as QLabel tries to guess whether it displays the text as plain text or as rich text. You may want to call setTextFormat() explicitly, e.g. in case you expect the text to be in plain format but cannot control the text source (for instance when displaying data loaded from the Web).

When the content is changed using any of these functions, any previous content is cleared.

By default, labels display left-aligned, vertically-centered text and images, where any tabs in the text to be displayed are automatically expanded. However, the look of a QLabel can be adjusted and fine-tuned in several ways.

The positioning of the content within the QLabel widget area can be tuned with setAlignment() and setIndent(). Text content can also wrap lines along word boundaries with setWordWrap(). For example, this code sets up a sunken panel with a two-line text in the bottom right corner (both lines being flush with the right side of the label):

label->setText(«first linensecond line»);

The properties and functions QLabel inherits from QFrame can also be used to specify the widget frame to be used for any given label.

A QLabel is often used as a label for an interactive widget. For this use QLabel provides a useful mechanism for adding an mnemonic (see QKeySequence) that will set the keyboard focus to the other widget (called the QLabel’s «buddy»). For example:

In this example, keyboard focus is transferred to the label’s buddy (the QLineEdit) when the user presses Alt+P. If the buddy was a button (inheriting from QAbstractButton), triggering the mnemonic would emulate a button click.

macintosh-label.png

Screenshot of a Macintosh style label

A label shown in the Macintosh Style Widget Gallery{Macintosh widget style}.

plastique-label.png

Screenshot of a Plastique style label

A label shown in the Plastique Style Widget Gallery{Plastique widget style}.

windowsxp-label.png

Screenshot of a Windows XP style label

A label shown in the Windows XP Style Widget Gallery{Windows XP widget style}.
See also
QLineEdit, QTextEdit, QPixmap, QMovie, {fowler}{GUI Design Handbook: Label}

Definition at line 55 of file qlabel.h.

◆ QLabel() [1/2]

QLabel::QLabel ( QWidget *  parent = 0,
Qt::WindowFlags  f = 0 
)
explicit

Constructs an empty label.

The parent and widget flag f, arguments are passed to the QFrame constructor.

See also
setAlignment(), setFrameStyle(), setIndent()

Definition at line 179 of file qlabel.cpp.

Referenced by QLabel().

181 {

183  d->init();

184 }

QFrame(QWidget *parent=0, Qt::WindowFlags f=0)

Constructs a frame widget with frame style NoFrame and a 1-pixel frame width.

The QLabel widget provides a text or image display.

◆ QLabel() [2/2]

QLabel::QLabel ( const QString &  text,
QWidget *  parent = 0,
Qt::WindowFlags  f = 0 
)
explicit

Constructs a label that displays the text, text.

The parent and widget flag f, arguments are passed to the QFrame constructor.

See also
setText(), setAlignment(), setFrameStyle(), setIndent()

Definition at line 194 of file qlabel.cpp.

196 {

198  d->init();

200 }

void setText(const QString &)

QFrame(QWidget *parent=0, Qt::WindowFlags f=0)

Constructs a frame widget with frame style NoFrame and a 1-pixel frame width.

The QLabel widget provides a text or image display.

Destroys the label.

Definition at line 286 of file qlabel.cpp.

287 {

289  d->clearContents();

290 }

The QLabel widget provides a text or image display.

◆ alignment()

Qt::Alignment QLabel::alignment ( ) const

◆ buddy()

◆ changeEvent()

void QLabel::changeEvent ( QEvent *  ev )
protectedvirtual

Reimplemented Function

Reimplemented from QFrame.

Definition at line 1513 of file qlabel.cpp.

1514 {

1517  if (d->isTextLabel) {

1518  if (d->control)

1519  d->control->document()->setDefaultFont(font());

1520  d->updateLabel();

1521  }

1523  d->control->setPalette(palette());

1525  d->updateLabel();

1526  }

1528 }

void changeEvent(QEvent *)

This event handler can be reimplemented to handle state changes.

The QLabel widget provides a text or image display.

Type type() const

Returns the event type.

◆ clear

void QLabel::clear ( )
slot

Clears any label contents.

Definition at line 420 of file qlabel.cpp.

421 {

423  d->clearContents();

424  d->updateLabel();

425 }

The QLabel widget provides a text or image display.

◆ contextMenuEvent()

This event handler, for event event, can be reimplemented in a subclass to receive widget context menu events.

The handler is called when the widget’s contextMenuPolicy is Qt::DefaultContextMenu.

The default implementation ignores the context event. See the QContextMenuEvent documentation for more details.

See also
event(), QContextMenuEvent customContextMenuRequested()

Reimplemented from QWidget.

Reimplemented in QmlJSDebugger::ToolBarColorBox.

Definition at line 1010 of file qlabel.cpp.

1011 {

1012 #ifdef QT_NO_CONTEXTMENU

1014 #else

1016  if (!d->isTextLabel) {

1017  ev->ignore();

1018  return;

1019  }

1020  QMenu *menu = d->createStandardContextMenu(ev->pos());

1021  if (!menu) {

1022  ev->ignore();

1023  return;

1024  }

1025  ev->accept();

1027  menu->popup(ev->globalPos());

1028 #endif

1029 }

The QLabel widget provides a text or image display.

#define Q_UNUSED(x)

Indicates to the compiler that the parameter with the specified name is not used in the body of a fun…

◆ event()

bool QLabel::event ( QEvent *  e )
protectedvirtual

◆ focusInEvent()

void QLabel::focusInEvent ( QFocusEvent *  ev )
protectedvirtual

Reimplemented Function

Reimplemented from QWidget.

Definition at line 1034 of file qlabel.cpp.

1035 {

1037  if (d->isTextLabel) {

1038  d->ensureTextControl();

1039  d->sendControlEvent(ev);

1040  }

1042 }

The QLabel widget provides a text or image display.

◆ focusNextPrevChild()

bool QLabel::focusNextPrevChild ( bool  next )
protectedvirtual

◆ focusOutEvent()

void QLabel::focusOutEvent ( QFocusEvent *  ev )
protectedvirtual

Reimplemented Function

em>Reimplemented Function

Reimplemented from QWidget.

Definition at line 1047 of file qlabel.cpp.

◆ hasScaledContents()

bool QLabel::hasScaledContents ( ) const

Definition at line 1543 of file qlabel.cpp.

1544 {

1546  return d->scaledcontents;

1547 }

The QLabel widget provides a text or image display.

◆ hasSelectedText()

bool QLabel::hasSelectedText ( ) const

◆ heightForWidth()

int QLabel::heightForWidth ( int  w ) const
virtual

◆ indent()

int QLabel::indent ( ) const

◆ keyPressEvent()

void QLabel::keyPressEvent ( QKeyEvent *  ev )
protectedvirtual

◆ linkActivated

void QLabel::linkActivated ( const QString &  link )
signal

◆ linkHovered

void QLabel::linkHovered ( const QString &  link )
signal

◆ margin()

int QLabel::margin ( ) const

◆ minimumSizeHint()

QSize QLabel::minimumSizeHint ( ) const
virtual

Reimplemented Function

em>Reimplemented Function

Reimplemented from QWidget.

Definition at line 958 of file qlabel.cpp.

◆ mouseMoveEvent()

void QLabel::mouseMoveEvent ( QMouseEvent *  ev )
protectedvirtual

◆ mousePressEvent()

void QLabel::mousePressEvent ( QMouseEvent *  ev )
protectedvirtual

◆ mouseReleaseEvent()

void QLabel::mouseReleaseEvent ( QMouseEvent *  ev )
protectedvirtual

◆ movie()

QMovie * QLabel::movie ( ) const

◆ openExternalLinks()

bool QLabel::openExternalLinks ( ) const

◆ paintEvent()

void QLabel::paintEvent ( QPaintEvent *  event )
protectedvirtual

This event handler can be reimplemented in a subclass to receive paint events passed in event.

A paint event is a request to repaint all or part of a widget. It can happen for one of the following reasons:

  • repaint() or update() was invoked,
  • the widget was obscured and has now been uncovered, or
  • many other reasons.

Many widgets can simply repaint their entire surface when asked to, but some slow widgets need to optimize by painting only the requested region: QPaintEvent::region(). This speed optimization does not change the result, as painting is clipped to that region during event processing. QListView and QTableView do this, for example.

Qt also tries to speed up painting by merging multiple paint events into one. When update() is called several times or the window system sends several paint events, Qt merges these events into one event with a larger region (see QRegion::united()). The repaint() function does not permit this optimization, so we suggest using update() whenever possible.

When the paint event occurs, the update region has normally been erased, so you are painting on the widget’s background.

The background can be set using setBackgroundRole() and setPalette().

Since Qt 4.0, QWidget automatically double-buffers its painting, so there is no need to write double-buffering code in paintEvent() to avoid flicker.

Note for the X11 platform: It is possible to toggle global double buffering by calling qt_x11_set_global_double_buffer(). For example,

Note
Generally, you should refrain from calling update() or repaint() inside a paintEvent(). For example, calling update() or repaint() on children inside a paintevent() results in undefined behavior; the child may or may not get a paint event.
Warning
If you are using a custom paint engine without Qt’s backingstore, Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will never be called; the backingstore will be used instead.
See also
event(), repaint(), update(), QPainter, QPixmap, QPaintEvent, {Analog Clock Example}

Reimplemented from QFrame.

Definition at line 1123 of file qlabel.cpp.

Referenced by QTipLabel::paintEvent().

1124 {

1130  cr.adjust(d->margin, d->margin, -d->margin, -d->margin);

1133 

1134 #ifndef QT_NO_MOVIE

1135  if (d->movie) {

1136  if (d->scaledcontents)

1137  style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));

1138  else

1139  style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());

1140  }

1141  else

1142 #endif

1143  if (d->isTextLabel) {

1144  QRectF lr = d->layoutRect().toAlignedRect();

1147 #ifndef QT_NO_STYLE_STYLESHEET

1148  if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) {

1149  cssStyle->styleSheetPalette(this, &opt, &opt.palette);

1150  }

1151 #endif

1152  if (d->control) {

1153 #ifndef QT_NO_SHORTCUT

1155  if (d->shortcutId != 0

1156  && underline != d->shortcutCursor.charFormat().fontUnderline()) {

1159  d->shortcutCursor.mergeCharFormat(fmt);

1160  }

1161 #endif

1162  d->ensureTextLayouted();

1163 

1166 

1167 

1171  painter.save();

1172  painter.translate(lr.x() + 1, lr.y() + 1);

1173  painter.setClipRect(lr.translated(-lr.x() — 1, -lr.y() — 1));

1175  layout->draw(&painter, context);

1176  painter.restore();

1177  }

1178 

1179 

1181 

1184 

1185  painter.save();

1186  painter.translate(lr.topLeft());

1187  painter.setClipRect(lr.translated(-lr.x(), -lr.y()));

1188  d->control->setPalette(context.palette);

1189  d->control->drawContents(&painter, QRectF(), this);

1190  painter.restore();

1191  } else {

1194  if (d->hasShortcut) {

1198  }

1200  }

1201  } else

1202 #ifndef QT_NO_PICTURE

1203  if (d->picture) {

1204  QRect br = d->picture->boundingRect();

1205  int rw = br.width();

1206  int rh = br.height();

1207  if (d->scaledcontents) {

1208  painter.save();

1209  painter.translate(cr.x(), cr.y());

1210  painter.scale((double)cr.width()/rw, (double)cr.height()/rh);

1211  painter.drawPicture(-br.x(), -br.y(), *d->picture);

1212  painter.restore();

1213  } else {

1214  int xo = 0;

1215  int yo = 0;

1217  yo = (cr.height()-rh)/2;

1219  yo = cr.height()-rh;

1221  xo = cr.width()-rw;

1223  xo = (cr.width()-rw)/2;

1224  painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);

1225  }

1226  } else

1227 #endif

1228  if (d->pixmap && !d->pixmap->isNull()) {

1230  if (d->scaledcontents) {

1231  if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) {

1232  if (!d->cachedimage)

1233  d->cachedimage = new QImage(d->pixmap->toImage());

1234  delete d->scaledpixmap;

1236  }

1237  pix = *d->scaledpixmap;

1238  } else

1239  pix = *d->pixmap;

1245  }

1246 }

virtual QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const =0

Returns a copy of the given pixmap, styled to conform to the specified iconMode and taking into accou…

The QPainter class performs low-level painting on widgets and other paint devices.

static QPixmap fromImage(const QImage &image, Qt::ImageConversionFlags flags=Qt::AutoColor)

Converts the given image to a pixmap using the specified flags to control the conversion.

qreal y() const

Returns the y-coordinate of the rectangle's top edge.

The QTextCharFormat class provides formatting information for characters in a QTextDocument.

const QColor & color() const

Returns the brush color.

The QFlag class is a helper data type for QFlags.

virtual int styleHint(StyleHint stylehint, const QStyleOption *opt=0, const QWidget *widget=0, QStyleHintReturn *returnData=0) const =0

Returns an integer representing the specified style hint for the given widget described by the provid…

QPointF topLeft() const

Returns the position of the rectangle's top-left corner.

int width() const

Returns the width of the rectangle.

virtual void drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole=QPalette::NoRole) const

Draws the given text in the specified rectangle using the provided painter and palette.

int height() const

Returns the height of the rectangle.

QPalette palette

the default color that is used for the text, when no color is specified.

const QColor & color(ColorGroup cg, ColorRole cr) const

Returns the color in the specified color group, used for the given color role.

The QRectF class defines a rectangle in the plane using floating point precision. …

const QBrush & light() const

Returns the light brush of the current color group.

The QStyleOption class stores the parameters used by QStyle functions.

void initFrom(const QWidget *w)

QSize size() const

Returns the size of the rectangle.

void adjust(int x1, int y1, int x2, int y2)

Adds dx1, dy1, dx2 and dy2 respectively to the existing coordinates of the rectangle.

The QImage class provides a hardware-independent image representation that allows direct access to th…

void drawFrame(QPainter *)

em>Reimplemented Function

QRect toRect() const

Returns a QRect based on the values of this rectangle.

QPalette palette

the palette that should be used when painting the control

virtual void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const

Draws the given pixmap in the specified rectangle, according to the specified alignment, using the provided painter.

static Qt::Alignment visualAlignment(Qt::LayoutDirection direction, Qt::Alignment alignment)

Transforms an alignment of Qt::AlignLeft or Qt::AlignRight without Qt::AlignAbsolute into Qt::AlignLe…

int y() const

Returns the y-coordinate of the rectangle's top edge.

qreal x() const

Returns the x-coordinate of the rectangle's left edge.

void setFontUnderline(bool underline)

If underline is true, sets the text format's font to be underlined; otherwise it is displayed non-und…

int x() const

Returns the x-coordinate of the rectangle's left edge.

void setColor(ColorGroup cg, ColorRole cr, const QColor &color)

Sets the color in the specified color group, used for the given color role, to the specified solid co…

The QAbstractTextDocumentLayout::PaintContext class is a convenience class defining the parameters us…

The QStyle class is an abstract base class that encapsulates the look and feel of a GUI…

The QRect class defines a rectangle in the plane using integer precision.

The QLabel widget provides a text or image display.

The QPixmap class is an off-screen image representation that can be used as a paint device…

QRectF translated(qreal dx, qreal dy) const

Returns a copy of the rectangle that is translated dx along the x axis and dy along the y axis…

virtual void draw(QPainter *painter, const PaintContext &context)=0

Draws the layout with the given painter using the given context.

The QAbstractTextDocumentLayout class is an abstract base class used to implement custom layouts for …

◆ picture()

const QPicture * QLabel::picture ( ) const

◆ pixmap()

const QPixmap* QLabel::pixmap ( ) const

◆ selectedText()

QString QLabel::selectedText ( ) const

◆ selectionStart()

int QLabel::selectionStart ( ) const

selectionStart() returns the index of the first selected character in the label or -1 if no text is selected.

See also
selectedText()

Note: The textInteractionFlags set on the label need to include either TextSelectableByMouse or TextSelectableByKeyboard.

Since
4.7em>Reimplemented Function

Definition at line 937 of file qlabel.cpp.

◆ setAlignment()

void QLabel::setAlignment ( Qt::Alignment  alignment )

◆ setBuddy()

void QLabel::setBuddy ( QWidget *  buddy )

Sets this label’s buddy to buddy.

When the user presses the shortcut key indicated by this label, the keyboard focus is transferred to the label’s buddy widget.

The buddy mechanism is only available for QLabels that contain text in which one character is prefixed with an ampersand, ‘&’. This character is set as the shortcut key. See the QKeySequence::mnemonic() documentation for details (to display an actual ampersand, use ‘&&’).

In a dialog, you might create two data entry widgets and a label for each, and set up the geometry layout so each label is just to the left of its data entry widget (its «buddy»), for example:

With the code above, the focus jumps to the Name field when the user presses Alt+N, and to the Phone field when the user presses Alt+P.

To unset a previously set buddy, call this function with buddy set to 0.

See also
buddy(), setText(), QShortcut, setAlignment()

Definition at line 1297 of file qlabel.cpp.

Referenced by QInputDialogPrivate::ensureLayout(), QFormLayout::insertRow(), QColorShower::QColorShower(), and QLabel().

1298 {

1301  if (d->isTextLabel) {

1302  if (d->shortcutId)

1304  d->shortcutId = 0;

1305  d->textDirty = true;

1306  if (buddy)

1307  d->updateShortcut();

1308  d->updateLabel();

1309  }

1310 }

QWidget * buddy() const

Returns this label's buddy, or 0 if no buddy is currently set.

The QLabel widget provides a text or image display.

◆ setIndent()

void QLabel::setIndent ( int  indent )

◆ setMargin()

void QLabel::setMargin ( int  margin )

◆ setMovie

void QLabel::setMovie ( QMovie *  movie )
slot

Sets the label contents to movie.

Any previous content is cleared. The label does NOT take ownership of the movie.

The buddy shortcut, if any, is disabled.

See also
movie(), setBuddy()

Definition at line 1385 of file qlabel.cpp.

1386 {

1388  d->clearContents();

1389 

1390  if (!movie)

1391  return;

1392 

1396 

1397 

1398 

1400  d->updateLabel();

1401 }

static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)

Creates a connection of the given type from the signal in the sender object to the method in the rece…

QMovie * movie() const

Returns a pointer to the label's movie, or 0 if no movie has been set.

The QRect class defines a rectangle in the plane using integer precision.

The QLabel widget provides a text or image display.

MovieState state() const

Returns the current state of QMovie.

The QSize class defines the size of a two-dimensional object using integer point precision.

◆ setNum [1/2]

void QLabel::setNum ( int  num )
slot

Sets the label contents to plain text containing the textual representation of integer num.

Any previous content is cleared. Does nothing if the integer’s string representation is the same as the current contents of the label.

The buddy shortcut, if any, is disabled.

See also
setText(), QString::setNum(), setBuddy()

Definition at line 490 of file qlabel.cpp.

491 {

495 }

void setText(const QString &)

The QString class provides a Unicode character string.

QString & setNum(short, int base=10)

This is an overloaded member function, provided for convenience. It differs from the above function o…

◆ setNum [2/2]

void QLabel::setNum ( double  num )
slot

Sets the label contents to plain text containing the textual representation of double num.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Any previous content is cleared. Does nothing if the double’s string representation is the same as the current contents of the label.

The buddy shortcut, if any, is disabled.

See also
setText(), QString::setNum(), setBuddy()

Definition at line 513 of file qlabel.cpp.

514 {

518 }

void setText(const QString &)

The QString class provides a Unicode character string.

QString & setNum(short, int base=10)

This is an overloaded member function, provided for convenience. It differs from the above function o…

◆ setOpenExternalLinks()

void QLabel::setOpenExternalLinks ( bool  open )

◆ setPicture

void QLabel::setPicture ( const QPicture &  picture )
slot

Sets the label contents to picture.

Any previous content is cleared.

The buddy shortcut, if any, is disabled.

See also
picture(), setBuddy()

Definition at line 469 of file qlabel.cpp.

470 {

472  d->clearContents();

473  d->picture = new QPicture(picture);

474 

475  d->updateLabel();

476 }

The QLabel widget provides a text or image display.

The QPicture class is a paint device that records and replays QPainter commands.

◆ setPixmap

void QLabel::setPixmap ( const QPixmap &  pixmap )
slot

◆ setScaledContents()

void QLabel::setScaledContents ( bool  enable )

Definition at line 1549 of file qlabel.cpp.

Referenced by QmlJSDebugger::ToolBarColorBox::ToolBarColorBox().

1550 {

1552  if ((bool)d->scaledcontents == enable)

1553  return;

1554  d->scaledcontents = enable;

1555  if (!enable) {

1556  delete d->scaledpixmap;

1557  d->scaledpixmap = 0;

1558  delete d->cachedimage;

1559  d->cachedimage = 0;

1560  }

1562 }

The QLabel widget provides a text or image display.

◆ setSelection()

void QLabel::setSelection ( int  start,
int  length 
)

Selects text from position start and for length characters.

See also
selectedText()

Note: The textInteractionFlags set on the label need to include either TextSelectableByMouse or TextSelectableByKeyboard.

Since
4.7

Definition at line 860 of file qlabel.cpp.

861 {

863  if (d->control) {

864  d->ensureTextPopulated();

868  d->control->setTextCursor(cursor);

869  }

870 }

The QTextCursor class offers an API to access and modify QTextDocuments.

The QLabel widget provides a text or image display.

void setPosition(int pos, MoveMode mode=MoveAnchor)

Moves the cursor to the absolute position in the document specified by pos using a MoveMode specified…

◆ setText

void QLabel::setText ( const QString &  text )
slot

Definition at line 366 of file qlabel.cpp.

Referenced by QBalloonTip::QBalloonTip(), QLabel(), QColorShower::retranslateStrings(), QTipLabel::reuseTip(), setNum(), setTextFormat(), QWizardHeader::setup(), and QWizardPrivate::updateLayout().

367 {

369  if (d->text == text)

370  return;

371 

373  d->control = 0;

374 

375  d->clearContents();

377  d->isTextLabel = true;

378  d->textDirty = true;

381 

382  d->control = oldControl;

383 

384  if (d->needTextControl()) {

385  d->ensureTextControl();

386  } else {

387  delete d->control;

388  d->control = 0;

389  }

390 

391  if (d->isRichText) {

393  } else {

394 

395  }

396 

397 #ifndef QT_NO_SHORTCUT

398  if (d->buddy)

399  d->updateShortcut();

400 #endif

401 

402  d->updateLabel();

403 

404 #ifndef QT_NO_ACCESSIBILITY

407 #endif

408 }

static void updateAccessibility(QObject *, int who, Event reason)

Notifies accessibility clients about a change in object's accessibility information.

Q_GUI_EXPORT bool mightBeRichText(const QString &)

Returns true if the string text is likely to be rich text; otherwise returns false.

static bool isEmpty(const char *str)

The QLabel widget provides a text or image display.

◆ setTextFormat()

◆ setTextInteractionFlags()

void QLabel::setTextInteractionFlags ( Qt::TextInteractionFlags  flags )

Definition at line 820 of file qlabel.cpp.

Referenced by QMessageBox::setInformativeText().

821 {

823  if (d->textInteractionFlags == flags)

824  return;

825  d->textInteractionFlags = flags;

830  else

832 

833  if (d->needTextControl()) {

834  d->ensureTextControl();

835  } else {

836  delete d->control;

837  d->control = 0;

838  }

839 

840  if (d->control)

841  d->control->setTextInteractionFlags(d->textInteractionFlags);

842 }

The QLabel widget provides a text or image display.

◆ setWordWrap()

void QLabel::setWordWrap ( bool  on )

◆ sizeHint()

QSize QLabel::sizeHint ( ) const
virtual

◆ text()

◆ textFormat()

◆ textInteractionFlags()

Qt::TextInteractionFlags QLabel::textInteractionFlags ( ) const

◆ wordWrap()

bool QLabel::wordWrap ( ) const

◆ QBalloonTip

◆ QMessageBoxPrivate

◆ QTipLabel

◆ alignment

Qt::Alignment QLabel::alignment

private

the alignment of the label’s contents

By default, the contents of the label are left-aligned and vertically-centered.

See also
text

Definition at line 62 of file qlabel.h.

◆ hasSelectedText

bool QLabel::hasSelectedText

private

whether there is any text selected

hasSelectedText() returns true if some or all of the text has been selected by the user; otherwise returns false.

By default, this property is false.

See also
selectedText()

Note: The textInteractionFlags set on the label need to include either TextSelectableByMouse or TextSelectableByKeyboard.

Since
4.7

Definition at line 68 of file qlabel.h.

◆ indent

the label’s text indent in pixels

If a label displays text, the indent applies to the left edge if alignment() is Qt::AlignLeft, to the right edge if alignment() is Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and to to the bottom edge if alignment() is Qt::AlignBottom.

If indent is negative, or if no indent has been set, the label computes the effective indent as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater than 0, the effective indent becomes half the width of the «x» character of the widget’s current font().

By default, the indent is -1, meaning that an effective indent is calculating in the manner described above.

See also
alignment, margin, frameWidth(), font()

Definition at line 65 of file qlabel.h.

◆ margin

the width of the margin

The margin is the distance between the innermost pixel of the frame and the outermost pixel of contents.

The default margin is 0.

See also
indent

Definition at line 64 of file qlabel.h.

◆ openExternalLinks

bool QLabel::openExternalLinks

private

◆ pixmap

◆ scaledContents

whether the label will scale its contents to fill all available space.

When enabled and the label shows a pixmap, it will scale the pixmap to fill the available space.

This property’s default is false.

Definition at line 61 of file qlabel.h.

◆ selectedText

the selected text

If there is no selected text this property’s value is an empty string.

By default, this property contains an empty string.

See also
hasSelectedText()

Note: The textInteractionFlags set on the label need to include either TextSelectableByMouse or TextSelectableByKeyboard.

Since
4.7

Definition at line 69 of file qlabel.h.

◆ text

the label’s text

If no text has been set this will return an empty string. Setting the text clears any previous content.

The text will be interpreted either as plain text or as rich text, depending on the text format setting; see setTextFormat(). The default setting is Qt::AutoText; i.e. QLabel will try to auto-detect the format of the text set.

If a buddy has been set, the buddy mnemonic key is updated from the new text.

Note that QLabel is well-suited to display small rich text documents, such as small documents that get their document specific settings (font, text color, link color) from the label’s palette and font properties. For large documents, use QTextEdit in read-only mode instead. QTextEdit can also provide a scroll bar when necessary.

Note
This function enables mouse tracking if text contains rich text.
See also
setTextFormat(), setBuddy(), alignment

Definition at line 58 of file qlabel.h.

Referenced by buddyString(), and QAccessibleDisplay::text().

◆ textFormat

◆ textInteractionFlags

Qt::TextInteractionFlags QLabel::textInteractionFlags

private

◆ wordWrap

the label’s word-wrapping policy

If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all.

By default, word wrap is disabled.

See also
text

Definition at line 63 of file qlabel.h.


The documentation for this class was generated from the following files:

  • /src/gui/widgets/qlabel.h
  • /src/gui/widgets/qlabel.cpp
  1. PyQt5 Label Widget
  2. PyQt5 QLabel Set Font
  3. PyQt5 Label Alignment

PyQt5 Tutorial - Label

We will learn to use PyQt5 label widget QLabel in this tutorial.

We’re going to add two labels to our window, where one of those labels is going to hold some text and one of those labels is going to hold an image.

import sys
from PyQt5 import QtWidgets, QtGui

def basicWindow():
    app = QtWidgets.QApplication(sys.argv)
    windowExample = QtWidgets.QWidget()
    labelA = QtWidgets.QLabel(windowExample)
    labelB = QtWidgets.QLabel(windowExample)
    labelA.setText('Label Example')
    labelB.setPixmap(QtGui.QPixmap('python.jpg'))
    windowExample.setWindowTitle('Label Example')
    windowExample.setGeometry(100, 100, 300, 200)
    labelA.move(100, 40)
    labelB.move(120, 120)
    windowExample.show()
    sys.exit(app.exec_())

basicWindow()

Where,

labelA = QtWidgets.QLabel(w)

The first label labelA is a QtWidgets.QtLabel and the QtWidgetsw is in parentheses because it tells the program that the label labelA is added to the window w.

labelA.setText('Label Example')

labelA.setText sets the text in the label.

windowExample.setGeometry(100, 100, 300, 200)

It sets the window size to be (300, 200) and left upper corner coordinate to be (100, 100). You could refer to the setGeometry explanation in last section.

labelA.move(100, 40)
labelB.move(120, 120)

move() method moves the label to the direction of right and down. Like labelA.move(100, 40) moves the labelA to the coordinate of (100, 40) relative to the left-upper corner of the window.

labelB.setPixmap(QtGui.QPixmap('globe.png'))

It displays images in the labelB. QPixmap is the module in QtGui and it takes an image of Qt.

PyQt5 Label

PyQt5 QLabel Set Font

In the example above, we use the default font in label widget, and you could specify the preferred font like size, weight and font family of the label text.

import sys
from PyQt5 import QtWidgets, QtGui

def basicWindow():
    app = QtWidgets.QApplication(sys.argv)
    windowExample = QtWidgets.QWidget()
    labelA = QtWidgets.QLabel(windowExample)
    labelB = QtWidgets.QLabel(windowExample)
    labelA.setText('Times Font')
    labelA.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Bold))
    labelB.setText('Arial Font')
    labelB.setFont(QtGui.QFont("Arial", 14, QtGui.QFont.Black))
    windowExample.setWindowTitle('Label Example')
    windowExample.setGeometry(100, 100, 300, 200)
    labelA.move(100, 40)
    labelB.move(100, 120)
    windowExample.show()
    sys.exit(app.exec_())

basicWindow()
labelA.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Bold))

setFont() method sets the font of the label. The QFont class specifies a font with specific attributes.

PyQt5 Label Set Font

PyQt5 Label Alignment

The label text is by default aligned to the left edge, and this property could be modified with the method QLabel.setAlignment().

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

def basicWindow():
    app = QtWidgets.QApplication(sys.argv)
    windowExample = QtWidgets.QWidget()

    labelLeft = QtWidgets.QLabel(windowExample)
    labelRight = QtWidgets.QLabel(windowExample)
    labelCenter = QtWidgets.QLabel(windowExample)

    labelLeft.setText('Left Align')
    labelRight.setText('Right Align')
    labelCenter.setText('Center Align')

    windowExample.setWindowTitle('Label Align Example')
    windowExample.setGeometry(100, 100, 300, 200)

    labelLeft.setFixedWidth(160)
    labelRight.setFixedWidth(160)
    labelCenter.setFixedWidth(160)

    labelLeft.setStyleSheet("border-radius: 25px;border: 1px solid black;")
    labelRight.setStyleSheet("border-radius: 25px;border: 1px solid black;")
    labelCenter.setStyleSheet("border-radius: 25px;border: 1px solid black;")

    labelLeft.setAlignment(QtCore.Qt.AlignLeft)
    labelRight.setAlignment(QtCore.Qt.AlignRight)
    labelCenter.setAlignment(QtCore.Qt.AlignCenter)
    
    labelLeft.move(80, 40)
    labelRight.move(80, 80)
    labelCenter.move(80, 120)    
    
    windowExample.show()
    sys.exit(app.exec_())

basicWindow()
labelLeft.setFixedWidth(160)
labelRight.setFixedWidth(160)
labelCenter.setFixedWidth(160)

It sets the fixed width to the three labels, otherwise, the label width is automatically set according to the label text length.

labelLeft.setStyleSheet("border-radius: 25px;border: 1px solid black;")

We could use CSS-alike style sheet to set the styles of the PyQt5 widgets. Here, the border of the label is set to be solid black with the border with of 1px, and the border radius is specified as 25px.

labelLeft.setAlignment(QtCore.Qt.AlignLeft)
labelRight.setAlignment(QtCore.Qt.AlignRight)
labelCenter.setAlignment(QtCore.Qt.AlignCenter)

The alignment property of the widget is set by the method setAlignment and its options are in the module PyQt5.QtCore.Qt, like

  • PyQt5.QtCore.Qt.AlignLeft
  • PyQt5.QtCore.Qt.AlignRight
  • PyQt5.QtCore.Qt.AlignCenter

As you could see from the image below, the labels are aligned according to their alignment properties.

PyQt5 Label Alignment

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить счет списания ипотеки сбербанк
  • Как изменить страну ворлд оф танкс
  • Как изменить стойку хускара
  • Как изменить стоимость товара на авито доставке
  • Как изменить стихию на сайте jut su

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии