Виджеты в pyqt5
Содержание:
Changes to Qt Widgets
- () and () signatures are changed to take arguments of type instead of .
- is removed as related getter and setter functions in QWidget and QApplication are removed. Input contexts are now platform-specific.
- () is deprecated. Use () instead.
- The classes are removed, and their members are merged with the respective base classes. The removed classes are left as typedefs for binary compatibility.
- QGraphicsItem and its derived classes can no longer pass a QGraphicsScene to the item’s constructor. Construct the item without a scene and call () to add the item to the scene.
- is removed. Use QAbstractProxyModel and the related classes instead. A copy of is available in the Ui Helpers repository.
Changes to QApplication
- is removed, because the introduction of QPA made it redundant.
- and virtual methods that were used for session management are removed. Connect to the and signals instead. Use () if the if your window needs to know whether it is being called during shutdown.
Changes to QStyle
- and are removed, and the () and () functions are made pure virtual now. The removed functions were introduced in Qt 4 for binary compatibility reasons.
- , , , and are replaced with a new fusion style. If your application depends on any of these removed styles, you can either use the qtstyleplugins project to get these styles or update your application to use the new fusion style. For more details about this change, see https://blog.qt.io/blog/2012/10/30/cleaning-up-styles-in-qt5-and-adding-fusion/.
- The following QStyle implementations have been made internal:
- QFusionStyle
- QGtkStyle
- QMacStyle
- QWindowsCEStyle
- QWindowsMobileStyle
- QWindowsStyle
- QWindowsVistaStyle
- QWindowsXPStyle
Instead of creating instances or inheriting these classes directly, use:
- QStyleFactory for creating instances of specific styles.
- QProxyStyle for customizing existing style implementations.
- QCommonStyle as a base for implementing full custom styles.
Changes to QHeaderView
The following functions are deprecated:
- — Use () instead.
- — Use () instead.
- — Use () instead.
- — Use () instead.
- — Use () instead.
- — Use () instead.
Changes to QAbstractItemView
- The derived classes now emit the signal on the left mouse click only, instead of all mouse clicks.
- The virtual () function signature now includes the roles that have changed. The signature is consistent with the signal in the model.
Класс QVBoxLayout
Класс QVBoxLayout предназначен для создания вертикального ряда из выравниваемых объектов. Добавление виджетов в компоновку осуществляется с помощью метода addWidget().
Заголовочный файл — verticalbox.h:
#pragma once
#include <QWidget>
class VerticalBox : public QWidget {
public:
VerticalBox(QWidget *parent = 0);
};
|
1 |
#pragma once classVerticalBoxpublicQWidget{ public VerticalBox(QWidget*parent=); }; |
В нашем примере у нас есть один менеджер вертикальный компоновки, в который мы устанавливаем пять кнопок. При этом параметры кнопок задаются так, чтобы они имели возможность расширяться в обоих направлениях.
Файл с реализацией — verticalbox.cpp:
#include «verticalbox.h»
#include <QVBoxLayout>
#include <QPushButton>
VerticalBox::VerticalBox(QWidget *parent)
: QWidget(parent) {
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setSpacing(1);
QPushButton *settings = new QPushButton(«Settings», this);
settings->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QPushButton *accounts = new QPushButton(«Accounts», this);
accounts->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QPushButton *loans = new QPushButton(«Loans», this);
loans->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QPushButton *cash = new QPushButton(«Cash», this);
cash->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QPushButton *debts = new QPushButton(«Debts», this);
debts->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
vbox->addWidget(settings);
vbox->addWidget(accounts);
vbox->addWidget(loans);
vbox->addWidget(cash);
vbox->addWidget(debts);
setLayout(vbox);
}
|
1 |
#include «verticalbox.h» VerticalBox::VerticalBox(QWidget*parent) QWidget(parent){ QVBoxLayout*vbox=newQVBoxLayout(this); vbox->setSpacing(1); QPushButton*settings=newQPushButton(«Settings»,this); settings->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); QPushButton*accounts=newQPushButton(«Accounts»,this); accounts->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); QPushButton*loans=newQPushButton(«Loans»,this); loans->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); QPushButton*cash=newQPushButton(«Cash»,this); cash->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); QPushButton*debts=newQPushButton(«Debts»,this); debts->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); vbox->addWidget(settings); vbox->addWidget(accounts); vbox->addWidget(loans); vbox->addWidget(cash); vbox->addWidget(debts); setLayout(vbox); } |
Создаём объект класса и устанавливаем интервал между дочерними виджетами в 1 пиксель:
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setSpacing(1);
|
1 |
QVBoxLayout*vbox=newQVBoxLayout(this); vbox->setSpacing(1); |
Теперь мы создаём кнопку и устанавливаем для неё политику размера . Дочерние виджеты управляются менеджером компоновки. По умолчанию кнопка растягивается по горизонтали и имеет фиксированный размер по вертикали. Если мы хотим изменить его, мы должны и для вертикали установить новую политику размера (). Как видите, в нашем случае кнопка будет расширяться в обоих направлениях:
QPushButton *settings = new QPushButton(«Settings», this);
settings->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
|
1 |
QPushButton*settings=newQPushButton(«Settings»,this); settings->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); |
Добавляем дочерние виджеты в менеджер компоновки при помощи метода addWidget():
vbox->addWidget(settings);
vbox->addWidget(accounts);
…
|
1 |
vbox->addWidget(settings); vbox->addWidget(accounts); … |
Сообщаем нашей программе использовать в качестве менеджера компоновки:
setLayout(vbox);
| 1 | setLayout(vbox); |
Главный файл приложения — main.cpp:
#include «verticalbox.h»
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
VerticalBox window;
window.resize(240, 230);
window.setWindowTitle(«VerticalBox»);
window.show();
return app.exec();
}
|
1 |
#include «verticalbox.h» intmain(intargc,char*argv){ QApplication app(argc,argv); VerticalBox window; window.resize(240,230); window.setWindowTitle(«VerticalBox»); window.show(); returnapp.exec(); } |
Результат:
Detailed Description
Table items are used to hold pieces of information for table widgets. Items usually contain text, icons, or checkboxes
The QTableWidgetItem class is a convenience class that replaces the class in Qt 3. It provides an item for use with the QTableWidget class.
Top-level items are constructed without a parent then inserted at the position specified by a pair of row and column numbers:
*newItem = new (tr("%1").arg(
pow(row, column+1)));
tableWidget->setItem(row, column, newItem);
Each item can have its own background brush which is set with the () function. The current background brush can be found with (). The text label for each item can be rendered with its own font and brush. These are specified with the () and () functions, and read with () and ().
By default, items are enabled, editable, selectable, checkable, and can be used both as the source of a drag and drop operation and as a drop target. Each item’s flags can be changed by calling () with the appropriate value (see ). Checkable items can be checked and unchecked with the () function. The corresponding () function indicates whether the item is currently checked.
Member Function Documentation
void QValueAxis::applyNiceNumbers()
Modifies the current range and number of tick marks on the axis to look nice. The algorithm considers numbers that can be expressed as a form of 1*10^n, 2* 10^n, or 5*10^n to be nice numbers. These numbers are used for setting spacing for the tick marks.
See also () and ().
This signal is emitted when the format of axis labels changes.
Note: Notifier signal for property .
void QValueAxis::maxChanged( max)
This signal is emitted when the maximum value of the axis, specified by max, changes.
Note: Notifier signal for property .
void QValueAxis::minChanged( min)
This signal is emitted when the minimum value of the axis, specified by min, changes.
Note: Notifier signal for property .
void QValueAxis::minorTickCountChanged(int minorTickCount)
This signal is emitted when the number of minor tick marks on the axis, specified by minorTickCount, changes.
Note: Notifier signal for property .
void QValueAxis::rangeChanged( min, max)
void QValueAxis::tickCountChanged(int tickCount)
This signal is emitted when the number of tick marks on the axis, specified by tickCount, changes.
Note: Notifier signal for property .
void QValueAxis::setRange( min, max)
Detailed Description
Tree widget items are used to hold rows of information for tree widgets. Rows usually contain several columns of data, each of which can contain a text label and an icon.
The QTreeWidgetItem class is a convenience class that replaces the QListViewItem class in Qt 3. It provides an item for use with the QTreeWidget class.
Items are usually constructed with a parent that is either a QTreeWidget (for top-level items) or a QTreeWidgetItem (for items on lower levels of the tree). For example, the following code constructs a top-level item to represent cities of the world, and adds a entry for Oslo as a child item:
*cities = new (treeWidget);
cities->setText(, tr("Cities"));
*osloItem = new (cities);
osloItem->setText(, tr("Oslo"));
osloItem->setText(1, tr("Yes"));
Items can be added in a particular order by specifying the item they follow when they are constructed:
*planets = new (treeWidget, cities);
planets->setText(, tr("Planets"));
Each column in an item can have its own background brush which is set with the () function. The current background brush can be found with (). The text label for each column can be rendered with its own font and brush. These are specified with the () and () functions, and read with () and ().
The main difference between top-level items and those in lower levels of the tree is that a top-level item has no (). This information can be used to tell the difference between items, and is useful to know when inserting and removing items from the tree. Children of an item can be removed with () and inserted at a given index in the list of children with the () function.
By default, items are enabled, selectable, checkable, and can be the source of a drag and drop operation. Each item’s flags can be changed by calling () with the appropriate value (see ). Checkable items can be checked and unchecked with the () function. The corresponding () function indicates whether the item is currently checked.
Changes to Qt OpenGL
Apart from the QGLWidget class, the Qt OpenGL module should not be used for new code. Instead, use the corresponding OpenGL classes in Qt GUI.
- QGLPixelBuffer is deprecated and implemented by using a hidden QGLWidget and a QOpenGLFramebufferObject. For offscreen rendering to a texture, switch to using QOpenGLFramebufferObject directly to improve performance.
- The default major version of QGLFormat is changed to 2 to align it with QSurfaceFormat. Applications that want to use a different version, should explicitly request it using ().
- and are removed.
- The parameter is removed from () functions.
- To ensure support on more platforms, stricter requirements have been introduced for doing threaded . First, you must call () at least once per each () call, so that the platform has a chance to synchronize resizing the surface. Second, before calling () or () in a separate thread, you must call () to explicitly let Qt know in which thread a QGLContext is currently being used. You also need to make sure that the context is not current in the current thread before moving it to a different thread.
Reimplemented Protected Functions
| virtual bool |
| virtual void |
| virtual void |
| virtual void |
Detailed Description
Each status indicator falls into one of three categories:
- Temporary — briefly occupies most of the status bar. Used to explain tool tip texts or menu entries, for example.
- Normal — occupies part of the status bar and may be hidden by temporary messages. Used to display the page and line number in a word processor, for example.
- Permanent — is never hidden. Used for important mode indications, for example, some applications put a Caps Lock indicator in the status bar.
QStatusBar lets you display all three types of indicators.
Typically, a request for the status bar functionality occurs in relation to a QMainWindow object. QMainWindow provides a main application window, with a menu bar, tool bars, dock widgets and a status bar around a large central widget. The status bar can be retrieved using the () function, and replaced using the () function.
Use the () slot to display a temporary message:
void MainWindow::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
To remove a temporary message, use the () slot, or set a time limit when calling (). For example:
void MainWindow::print()
{
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printdialog)
QTextDocument *document = textEdit->document();
QPrinter printer;
QPrintDialog dlg(&printer, this);
if (dlg.exec() != QDialog::Accepted) {
return;
}
document->print(&printer);
statusBar()->showMessage(tr("Ready"), 2000);
#endif
}
Use the () function to retrieve the temporary message currently shown. The QStatusBar class also provide the () signal which is emitted whenever the temporary status message changes.
Normal and Permanent messages are displayed by creating a small widget (QLabel, QProgressBar or even QToolButton) and then adding it to the status bar using the () or the () function. Use the () function to remove such messages from the status bar.
statusBar()->addWidget(new MyReadWriteIndication);
By default QStatusBar provides a QSizeGrip in the lower-right corner. You can disable it using the () function. Use the () function to determine the current status of the size grip.
See also QMainWindow, QStatusTipEvent, , and Application Example.
sizeGripEnabled : bool
This property holds whether the QSizeGrip in the bottom-right corner of the status bar is enabled
The size grip is enabled by default.
Access functions:
| bool |
| void |
Signals
| void |
| void |
| void |
| void |
| void |
| void |
| void |
| void |
| void |
Detailed Description
A value axis can be set up to show an axis line with tick marks, grid lines, and shades. The values on the axis are drawn at the positions of tick marks.
The following example code illustrates how to use the QValueAxis class:
QChartView *chartView = new QChartView;
QLineSeries *series = new QLineSeries;
chartView->chart()->addSeries(series);
*axisX = new ;
axisX->setRange(10, 20.5);
axisX->setTickCount(10);
axisX->setLabelFormat("%.2f");
chartView->chart()->setAxisX(axisX, series);
Member Type Documentation
enum QValueAxis::TickType
This enum describes how the ticks and labels are positioned on the axis.
| Constant | Value | Description |
|---|---|---|
| Ticks are placed according to and values. | ||
| Ticks are placed evenly across the axis range. The value specifies the number of ticks. |
Property Documentation
labelFormat : QString
This property holds the label format of the axis.
The format string supports the following conversion specifiers, length modifiers, and flags provided by in the standard C++ library: d, i, o, x, X, f, F, e, E, g, G, c.
If is , the supported specifiers are limited to: d, e, E, f, g, G, and i. Also, only the precision modifier is supported. The rest of the formatting comes from the default QLocale of the application.
Access functions:
| QString |
| void |
Notifier signal:
| void |
See also ().
max :
This property holds the maximum value on the axis.
When setting this property, the minimum value is adjusted if necessary, to ensure that the range remains valid.
Access functions:
| qreal |
| void |
Notifier signal:
| void |
min :
This property holds the minimum value on the axis.
When setting this property, the maximum value is adjusted if necessary, to ensure that the range remains valid.
Access functions:
| qreal |
| void |
Notifier signal:
| void |
minorTickCount : int
This property holds the number of minor tick marks on the axis. This indicates how many grid lines are drawn between major ticks on the chart. Labels are not drawn for minor ticks. The default value is 0.
Access functions:
| int |
| void |
Notifier signal:
| void |
tickAnchor :
This property holds the base value where the dynamically placed tick marks and labels are started from.
This property was introduced in Qt 5.12.
Access functions:
| qreal |
| void |
Notifier signal:
| void |
tickCount : int
This property holds the number of tick marks on the axis. This indicates how many grid lines are drawn on the chart. The default value is 5, and the number cannot be less than 2.
Access functions:
| int |
| void |
Notifier signal:
| void |
tickInterval :
This property holds the interval between dynamically placed tick marks and labels.
This property was introduced in Qt 5.12.
Access functions:
| qreal |
| void |
Notifier signal:
| void |
tickType :
This property holds the positioning method of tick and labels.
This property was introduced in Qt 5.12.
Access functions:
| QValueAxis::TickType |
| void |
Notifier signal:
| void |
Member Function Documentation
Constructs a status bar with a size grip and the given parent.
See also ().
Removes any temporary message being shown.
See also (), (), and ().
void QStatusBar::messageChanged(const QString &message)
This signal is emitted whenever the temporary status message changes. The new temporary message is passed in the message parameter which is a null-string when the message has been removed.
See also () and ().
void QStatusBar::showMessage(const QString &message, int timeout = 0)
Hides the normal status indications and displays the given message for the specified number of milli-seconds (timeout). If timeout is 0 (default), the message remains displayed until the () slot is called or until the showMessage() slot is called again to change the message.
Note that showMessage() is called to show temporary explanations of tool tip texts, so passing a timeout of 0 is not sufficient to display a .
See also (), (), and ().
void QStatusBar::addPermanentWidget( *widget, int stretch = 0)
Adds the given widget permanently to this status bar, reparenting the widget if it isn’t already a child of this QStatusBar object. The stretch parameter is used to compute a suitable size for the given widget as the status bar grows and shrinks. The default stretch factor is 0, i.e giving the widget a minimum of space.
Permanently means that the widget may not be obscured by temporary messages. It is is located at the far right of the status bar.
See also (), (), and ().
void QStatusBar::addWidget( *widget, int stretch = 0)
Adds the given widget to this status bar, reparenting the widget if it isn’t already a child of this QStatusBar object. The stretch parameter is used to compute a suitable size for the given widget as the status bar grows and shrinks. The default stretch factor is 0, i.e giving the widget a minimum of space.
The widget is located to the far left of the first permanent widget (see ()) and may be obscured by temporary messages.
See also (), (), and ().
Returns the temporary message currently shown, or an empty string if there is no such message.
See also ().
Ensures that the right widgets are visible.
Used by the () and () functions.
int QStatusBar::insertPermanentWidget(int index, *widget, int stretch = 0)
Inserts the given widget at the given index permanently to this status bar, reparenting the widget if it isn’t already a child of this QStatusBar object. If index is out of range, the widget is appended (in which case it is the actual index of the widget that is returned).
The stretch parameter is used to compute a suitable size for the given widget as the status bar grows and shrinks. The default stretch factor is 0, i.e giving the widget a minimum of space.
Permanently means that the widget may not be obscured by temporary messages. It is is located at the far right of the status bar.
This function was introduced in Qt 4.2.
See also (), (), and ().
int QStatusBar::insertWidget(int index, *widget, int stretch = 0)
Inserts the given widget at the given index to this status bar, reparenting the widget if it isn’t already a child of this QStatusBar object. If index is out of range, the widget is appended (in which case it is the actual index of the widget that is returned).
The stretch parameter is used to compute a suitable size for the given widget as the status bar grows and shrinks. The default stretch factor is 0, i.e giving the widget a minimum of space.
The widget is located to the far left of the first permanent widget (see ()) and may be obscured by temporary messages.
This function was introduced in Qt 4.2.
See also (), (), and ().
Reimplements: (QPaintEvent *event).
Shows the temporary message, if appropriate, in response to the paint event.
void QStatusBar::reformat()
Changes the status bar’s appearance to account for item changes.
Special subclasses may need this function, but geometry management will usually take care of any necessary rearrangements.
void QStatusBar::removeWidget( *widget)
Removes the specified widget from the status bar.
Note: This function does not delete the widget but hides it. To add the widget again, you must call both the () and () functions.
See also (), (), and ().
Changes to Qt Network
- The enum value is renamed as .
- The , , , and classes are removed. Use QNetworkAccessManager instead.
- The and classes are no longer exported. Use QNetworkAccessManager instead. Programs that require raw FTP or HTTP streams can use the and compatibility add-on modules that provide the and classes as they existed in Qt 4.
- () and () are virtual now, and and are removed.
- () now takes arguments of type instead of an .
- is removed. Use the instead.
Changes to QSslCertificate
- () and () now return QStringList instead of a QString. This change makes searching the required information a lot easier than scanning a long string.
- () is deprecated. Use () instead to avoid binary breaks in the future.
- () is deprecated. Use () instead.
Property Documentation
alignment : Qt::Alignment
This property holds the alignment of the label’s contents
By default, the contents of the label are left-aligned and vertically-centered.
Access functions:
| Qt::Alignment |
| void |
See also .
hasSelectedText : const bool
This property holds whether there is any text selected
hasSelectedText() returns if some or all of the text has been selected by the user; otherwise returns .
By default, this property is .
Note: The set on the label need to include either TextSelectableByMouse or TextSelectableByKeyboard.
This property was introduced in Qt 4.7.
Access functions:
| bool |
See also ().
indent : int
This property holds the label’s text indent in pixels
If a label displays text, the indent applies to the left edge if () is , to the right edge if () is , to the top edge if () is , and to the bottom edge if () is .
If indent is negative, or if no indent has been set, the label computes the effective indent as follows: If () is 0, the effective indent becomes 0. If () is greater than 0, the effective indent becomes half the width of the «x» character of the widget’s current ().
By default, the indent is -1, meaning that an effective indent is calculating in the manner described above.
Access functions:
| int |
| void |
See also , , (), and ().
margin : int
This property holds 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.
Access functions:
| int |
| void |
See also .
openExternalLinks : bool
Specifies whether QLabel should automatically open links using () instead of emitting the () signal.
Note: The set on the label need to include either LinksAccessibleByMouse or LinksAccessibleByKeyboard.
The default value is false.
This property was introduced in Qt 4.2.
Access functions:
| bool |
| void |
See also ().
pixmap : QPixmap
This property holds the label’s pixmap
If no pixmap has been set this will return nullptr.
Setting the pixmap clears any previous content. The buddy shortcut, if any, is disabled.
Access functions:
| const QPixmap * |
| void |
scaledContents : bool
This property holds 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.
Access functions:
| bool |
| void |
selectedText : const QString
This property holds 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.
Note: The set on the label need to include either TextSelectableByMouse or TextSelectableByKeyboard.
This property was introduced in Qt 4.7.
Access functions:
| QString |
See also ().
text : QString
This property holds 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 (). The default setting is ; i.e. QLabel will try to auto-detect the format of the text set. See Supported HTML Subset for the
definition of rich text.
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.
Access functions:
| QString |
| void |
See also (), (), and .
textFormat : Qt::TextFormat
This property holds the label’s text format
See the enum for an explanation of the possible options.
The default format is .
Access functions:
| Qt::TextFormat |
| void |
See also ().
textInteractionFlags : Qt::TextInteractionFlags
Specifies how the label should interact with user input if it displays text.
If the flags contain the focus policy is also automatically set to . If is set then the focus policy is set to .
The default value is .
This property was introduced in Qt 4.2.
Access functions:
| Qt::TextInteractionFlags |
| void |
wordWrap : bool
This property holds the label’s word-wrapping policy
If this property is then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all.
By default, word wrap is disabled.
Access functions:
| bool |
| void |
Detailed Description
A text block encapsulates a block or paragraph of text in a QTextDocument. QTextBlock provides read-only access to the block/paragraph structure of QTextDocuments. It is mainly of use if you want to implement your own layouts for the visual representation of a QTextDocument, or if you want to iterate over a document and write out the contents in your own custom format.
Text blocks are created by their parent documents. If you need to create a new text block, or modify the contents of a document while examining its contents, use the cursor-based interface provided by QTextCursor instead.
Each text block is located at a specific () in a (). The contents of the block can be obtained by using the () function. The () function determines the block’s size within the document (including formatting characters). The visual properties of the block are determined by its text (), its (), and its ().
The () and () functions enable iteration over consecutive valid blocks in a document under the condition that the document is not modified by other means during the iteration process. Note that, although blocks are returned in sequence, adjacent blocks may come from different places in the document structure. The validity of a block can be determined by calling ().
QTextBlock provides comparison operators to make it easier to work with blocks: () compares two block for equality, () compares two blocks for inequality, and () determines whether a block precedes another in the same document.
Описание Свойств
alignment :
Данное свойство содержит выравнивание содержимого метки.
Функции доступа:
-
Qt::Alignment alignment () const
-
void setAlignment ( Qt::Alignment )
См. также .
indent : int
Данное свойство содержит отступ текста от края в пикселях.
Если метка отображает текст, то отступ располагается слева, если () равно ; справа, если () равно ; сверху, если () равно ; снизу, если () равно .
Если затребованное пространство отрицательно или не установлено, то метка вычисляет требуемый отступ следующим образом: Если () равно 0, то отступ будет равен 0. Если () больше 0, то отступ будет равен половине ширины символа «x» в текущем () виджета.
Функции доступа:
-
int indent () const
-
void setIndent ( int )
См. также , , () и ().
margin : int
Данное свойство содержит ширину краев.
Ширина краев — это расстояние от внутренней границы рамки до внешней границы содержимого.
По умолчанию ширина краев равна 0.
Функции доступа:
-
int margin () const
-
void setMargin ( int )
См. также .
pixmap : QPixmap
Данное свойство содержит пиксельную карту метки.
Если пиксельная карта не была установлена, то возвращается пустая карта.
При установке пиксельной карты стирается все все ранее содержащееся в метке. Если было установлено горячее сочетание клавиш для дружественного элемента, оно также удаляется.
Функции доступа:
-
const QPixmap * pixmap () const
-
void setPixmap ( const QPixmap & )
scaledContents : bool
Данное свойство указывает, будет ли метка изменять масштаб содержимого для того, чтобы заполнить все доступное пространство.
Если масштабирование позволено и метка содержит пиксельную карту, то пиксельная карта будет растянута для того, чтобы заполнить все доступное пространство.
Данное свойство по умолчанию имеет значение false.
Функции доступа:
-
bool hasScaledContents () const
-
void setScaledContents ( bool )
text : QString
Данное свойство содержит текст метки.
Если текст не был установлен, то возвращается пустая строка. При установке текста удаляется все ранее содержащееся в метке если оно не тоже самое.
В зависимости от установок формата, текст будет интерпретирован либо как простой текст, либо как форматированный; см. (). По умолчанию формат установлен как , т.е. QLabel будет пытаться автоматически распознать форматирование текста.
Если текст интрепретируется как простой текст и для метки задан дружественный элемент, то мнемоническое сочетание клавиш для дружественного элемента будет установлено в соответствии с новым текстом.
Если автоматическое изменение размера позволено, то метка сама поменяет размер.
Обратите внимание, что Qlabel хорошо подходит для отображения небольших форматированных документов, т.е. таких небольших документов, для которых заданы определенные значения (шрифт, цвет текста, цвет ссылок) из палитры метки и свойств шрифта
Для отображения больших документов, используйте QTextEdit в режиме «только чтение». QTextEdit при изменении размера меньше мерцает и может предоставить полосу прокрутки, если это необходимо.
Функции доступа:
-
QString text () const
-
void setText ( const QString & )
См. также (), () и .
textFormat :
Данное свойство содержит формат текста метки.
Для получения информации о доступных значениях, см. описание перечисления .
Формат по умолчанию равен .
Функции доступа:
-
Qt::TextFormat textFormat () const
-
void setTextFormat ( Qt::TextFormat )
См. также ().
wordWrap : bool
Данное свойство указывает, может ли метка переностиь текст по словам.
Если данное свойство равно true, то текст метки переносится, если необходимо, по словам; иначе не переносится вообще.
Функции доступа:
-
bool wordWrap () const
-
void setWordWrap ( bool on )