QWidget Class Reference
|
|
|
Класс QWidget является базовым для всех объектов пользовательского интерфейса.
Виджет - это элементарный объект пользовательского интерфейса: он получает события мыши, клавиатуры и другие события от оконной системы и рисует свое изображение на экране. Каждый виджет имеет прямоугольную форму, и все они отсортированы в порядке наложения (Z-order). Виджет ограничен своим родителем и другими виджетами, расположенными перед ним.
Виджет, который не встроен в родителя, называется окном. Usually, windows have a frame and a title bar, although it is also possible to create windows without such decoration using suitable window flags). В Qt QMainWindow и разнообразные подклассы QDialog являются наиболее распространёнными типами окон.
Каждый конструктор виджета принимает один или два стандартных аргумента:
QWidget имеет много функций, но большинство из них не имеет непосредственного применения, например, QWidget имеет свойство шрифта, но никогда не использует его для самого себя. There are many subclasses which provide real functionality, such as QLabel, QPushButton, QListWidget, and QTabWidget.
Виджет без родительского виджета всегда является независимым (виджетом верхнего уровня. For these widgets, setWindowTitle() and setWindowIcon() set the title bar and icon respectively.
Виджеты, не являющиеся окнами, являются дочерними виджетами своего родительского виджета. Большинство виджетов в Qt are приимущественно используются как дочернии виджеты. For example, it is possible to display a button as a top-level window, but most people prefer to put their buttons inside other widgets, such as QDialog.

The above diagram shows a QGroupBox widget being used to hold various child widgets in a layout provided by QGridLayout. The QLabel child widgets have been outlined to indicate their full sizes.
Если вы хотите использовать QWidget, который охватывает дочерние виджеты, это значит вам нужно добавить компановщик в родительский виджет. See Layout Classes for more information about these.
Если виджет сипользуется как контейнер, объединяющий некоторое число дочерних виджетов, он называется комбинированным виджетом. These can be created by constructing a widget with the required visual properties - a QFrame, for example - and adding child widgets to it, usually managed by a layout. The above diagram shows such a composite widget that was created using Qt Designer.
Composite widgets can also be created by subclassing a standard widget, such as QWidget or QFrame, and adding the necessary layout and child widgets in the constructor of the subclass. Many of the examples provided with Qt use this approach, and it is also covered in the Qt Tutorial.
Since QWidget is a subclass of QPaintDevice, subclasses can be used to display custom content that is composed using a series of painting operations with an instance of the QPainter class. This approach contrasts with the canvas-style approach used by the Graphics View Framework where items are added to a scene by the application and are rendered by the framework itself.
Each widget performs all painting operations from within its paintEvent() function. Она вызывется, когда возникает необходимость перерисовать виджет, по причине некоторых внешних изменений или по требованию приложения.
The Analog Clock example shows how a simple widget can handle paint events.
When implementing a new widget, it is almost always useful to reimplement sizeHint() to provide a reasonable default size for the widget and to set the correct size policy with setSizePolicy().
По умолчанию, определение размеров виджетов, у которых не определены предпочтительные размеры, будет происходить в соответствии с пространством, которое требуют его дочерние виджеты.
Политика размеров позволяет вам обеспечить хорошее поведение для системы компановки, до такой степени, что другие виджеты могут легко управлять вашим. По умолчанию политика размеров подразумевает, что сакмое лучшее, если боьшинство виджетов будет иметь свой предпочтительный размер.
Виджеты получают события, которые порождаются типичными действиями пользователя. Qt delivers events to widgets by calling specific event handler functions with instances of QEvent subclasses containing information about each event.
Если ваш виджет является всего лишь контейнером для дочерних виджетов, вам, скорей всго, не понадобится перегружать никаких обработчиков событий. If you want to detect a mouse click in a child widget call the child's underMouse() function inside the widget's mousePressEvent().
The Scribble example implements a wider set of events to handle mouse movement, button presses, and window resizing.
You will need to supply the behavior and content for your own widgets, but здесь перечисленны которые получает QWidget, начиная с самых общих:
У виджетов, которые разрешают воод с клавиатуры, нужно перегрузить немного больше функций:
Некоторым виджетам тербуется перегрузить менее общие обработчики событий:
There are also some rather obscure events described in the QEvent::Type documentation. You need to reimplement event() directly to handle these. The default implementation of event() handles Tab and Shift+Tab (to move the keyboard focus), and passes on most other events to one of the more specialized handlers above.
Events and the mechanism used to deliver them are covered in the Events and Event Filters document.
In addition to the standard widget styles for each platform, widgets can also be styled according to rules specified in a style sheet. Эта особенность позволит вам визуально подчеркнуть назначение виджета; например, кнопка может быть выполнена в особом стиле, чтобы подчеркнуть, что она выполняет функцию удаления.
The use of widgets style sheets is described in more detail in Qt Style Sheets.
From Qt 4.0, QWidget automatically double-buffers its painting, so there's no need to write double-buffering code in paintEvent() to avoid flicker. Additionally, it became possible for widgets to propagate their contents to children, in order to enable transparency effects, by setting the Qt::WA_ContentsPropagated widget attribute - this is now deprecated in Qt 4.1.
В Qt 4.1 содержимое родительского виджета размножается по умолчанию в каждом из его дочерних виджетов. Пользовательские виджеты могут использовать эту особенность для перерисовки только тех областей, где это требуется (для не прямоугольных дочерних виджетов), или при использовании рисования цветами, которые имеют неполный альфа-канал. Следующий рисунок показывает, как, меняя атрибуты и свойства пользовательского виджета, можно добиться совершенно разных эффектов.

In the above diagram, a semi-transparent rectangular child widget with an area removed is constructed and added to a parent widget (a QLabel showing a pixmap) then different properties and widget attributes are set to achieve different effects:
For rapidly updating custom widgets with simple background colors, such as real-time plotting or graphing widgets, it is better to define a suitable background color (using setBackgroundRole() with the QPalette::Window role), set the autoFillBackground property, and only implement the necessary drawing functionality in the widget's paintEvent().
For rapidly updating custom widgets that constantly paint over their entire areas with opaque content, such as video streaming widgets, it is better to set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead associated with repainting the widget's background.
If a widget has both the Qt::WA_OpaquePaintEvent widget attribute and the autoFillBackground property set, the Qt::WA_OpaquePaintEvent attribute takes precedence. Вы должны выбрать и установить только одно необходимое вам требование.
В Qt 4.1 содержимое родительских виджетов также передается в стандартные виджеты Qt. Это может привести к неожиданным результатам, если родительский виджет оформлен нестандартным образом, как показано на рисунке ниже.

Возможностей для разнообразного поведения при перерисовке стандартных виджетов без создания подклассов значительно меньше, чем возможностей у пользовательских виджетов. Usually, the desired appearance of a standard widget can be achieved by setting its autoFillBackground property.
See also QEvent, QPainter, QGridLayout, and QBoxLayout.
This enum describes how to render the widget when calling QWidget::render().
| Константа | Значение | Описание |
|---|---|---|
| QWidget::DrawWindowBackground | 0x1 | If you enable this option, the widget's background is rendered into the target even if autoFillBackground is not set. По умолчанию, эта опция разрешена. |
| QWidget::DrawChildren | 0x2 | Если вы разрешаете эту опцию, дети виджета будут окрашены в переданный в функцию цвет. По умолчанию, эта опция разрешена. |
| QWidget::IgnoreMask | 0x4 | If you enable this option, the widget's QWidget::mask() is ignored when rendering into the target. По умолчанию эта опция запрещена. |
Данное перечисление было введено в Qt 4.3.
The RenderFlags type is a typedef for QFlags<RenderFlag>. Он хранит комбинацию (по ИЛИ) значений RenderFlag.
Это свойство указывает, разрешен ли для этого виджета просмотр событий.
Setting this property to true announces to the system that this widget may be able to accept drop events.
If the widget is the desktop (windowType() == Qt::Desktop), this may fail if another application is using the desktop; you can call acceptDrops() to test if this occurs.
Warning: Do not modify this property in a drag and drop event handler.
По умолчанию, это свойство равно false.
Функции доступа:
See also Drag and Drop.
Это свойство содержит описание виджета как помощь при разработке.
По умолчанию, это свойство содержит пустую строку.
Функции доступа:
See also QAccessibleInterface::text().
Это свойство содержит имя виджета, предназначенное для помощи при разработке.
This property is used by accessible clients to identify, find, or announce the widget for accessible clients.
По умолчанию, это свойство содержит пустую строку.
Функции доступа:
See also QAccessibleInterface::text().
Данное свойство указывает, заливается ли фон виджета автоматически.
If enabled, this will cause Qt to fill the background of the widget before invoking the paint event. The color used is defined by the QPalette::Window color role from the widget's palette.
Кроме того, Windows всегда заливает QPalette::Window, если не установлены атрибуты WA_OpaquePaintEvent или WA_NoSystemBackground.
Warning: Use this property with caution in conjunction with Qt Style Sheets. Когда виджет имеет таблицу стилей с правильно определенными фоном и рамкой, это свойство автоматически отменяется.
По умолчанию, это свойство равно false.
Это свойство было введено в Qt 4.1.
Функции доступа:
See also Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground, and Transparency and Double Buffering.
Это свойство определяет базовые размеры виджета.
The base size is used to calculate a proper widget size if the widget defines sizeIncrement().
By default, for a newly-created widget, this property contains a size with zero width and height.
Функции доступа:
See also setSizeIncrement().
Это свойство определяет прямоугольник, охватывающий детей виджета.
Погашенные дети не охватываются.
By default, for a widget with no children, this property contains a rectangle with zero width and height located at the origin.
Функции доступа:
See also childrenRegion() and geometry().
Это свойство содержит комбинацию регионов, которые занимают дети виджета.
Погашенные дети не охватываются.
By default, for a widget with no children, this property contains an empty region.
Функции доступа:
See also childrenRect(), geometry(), and mask().
Это свойство содержит информацию, как виджет должен отображать контекстное меню.
The default value of this property is Qt::DefaultContextMenu, which means the contextMenuEvent() handler is called. Other values are Qt::NoContextMenu, Qt::PreventContextMenu, Qt::ActionsContextMenu, and Qt::CustomContextMenu. With Qt::CustomContextMenu, the signal customContextMenuRequested() is emitted.
Функции доступа:
See also contextMenuEvent(), customContextMenuRequested(), and actions().
Это свойство показывает, какой формы должен быть курсор для виджета.
Курсор мыши принимает заданную форму, когда нахожится на виджете. Смотрите список предопределённых объектов курсора для диапазона полезных форм.
Для виджета-редактора можно использовать I-образный курсор:
setCursor(Qt::IBeamCursor);
Если никаной курсор не установлен или был вызов функции unsetCursor(), используется родительский курсор.
By default, this property contains a cursor with the Qt::ArrowCursor shape.
Функции доступа:
See also QApplication::setOverrideCursor().
Это свойство показывает, разрешен виджет или нет.
Разрешенный виджет обрабатывает события от мишки и клавиатуры; Запрещенный виджет не имеет такой возможности.
Некоторые виджеты поразному отображают себя в зависимости от того, разрешены они или нет. Например, кнопка может отображать свою надпись тусклым цветом. If your widget needs to know when it becomes enabled or disabled, you can use the changeEvent() with type QEvent::EnabledChange.
Запрет обновления у виджета означает запрет обновления у всех его детей. Разрешение, соответственно, разрешает обновление всем детям, исключая те, которые явно запрещены.
По умолчанию это свойство равно true.
Функции доступа:
See also isEnabledTo(), QKeyEvent, QMouseEvent, and changeEvent().
Это свойство показывает имеет ли виджет (или его заместитель) фокус ввода с клавиатуры.
По умолчанию, это свойство равно false.
Note: Obtaining the value of this property for a widget is effectively equivalent to checking whether QApplication::focusWidget() refers to the widget.
Функции доступа:
See also setFocus(), clearFocus(), setFocusPolicy(), and QApplication::focusWidget().
Это свойство определяет способ получения фокуса ввода с клавиатуры.
The policy is Qt::TabFocus if the widget accepts keyboard focus by tabbing, Qt::ClickFocus if the widget accepts focus by clicking, Qt::StrongFocus if it accepts both, and Qt::NoFocus (the default) if it does not accept focus at all.
Вы должны разрешить виджету принимать фокус от клавиатуры, если он принимает события от клавиатуры. Обычно это делается в конструкторе виджета. Например, конструктор QLineEdit вызывает setFocusPolicy(Qt::StrongFocus).
Функции доступа:
Смотрите также focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent() и enabled.
Это свойство определяет текущий шрифт для виджета.
The fontInfo() function reports the actual font that is being used by the widget.
As long as no special font has been set, or after setFont(QFont()) is called, this is either a special font for the widget class, the parent's font or (if this widget is a top level widget), the default application font.
Этот кусок кода демонстрирует, как установить шрифт helvetica высотой 12, полужирный:
QFont font("Helvetica", 12, QFont::Bold);
setFont(font);
Note that when a child widget is given a different font to that of its parent widget, it will still inherit the parent's font properties unless these have been set explicitly on the child's font. Например, если родительский шрифт является полужирным, дочерний шрифт также будет полужирным, если не определить иначе, как в показано здесь:
QFont font; font.setBold(false); setFont(font);
В добавок к установке шрифта setFont() информирует все дочерние виджеты о прои зошедших переменах.
Note: If Qt Style Sheets are used on the same widget as setFont(), style sheets will take precedence if the settings conflict.
Функции доступа:
See also fontInfo() and fontMetrics().
Это свойство содержит геометрию виджета относительно родителя, включая любую оконную рамку.
See the Window Geometry documentation for an overview of geometry issues with windows.
By default, this property contains a value that depends on the user's platform and screen geometry.
Функции доступа:
See also geometry(), x(), y(), and pos().
Это свойство содержит размер виджента включая оконную рамку.
By default, this property contains a value that depends on the user's platform and screen geometry.
Функции доступа:
This property holds whether the widget is shown in full screen mode.
A widget in full screen mode occupies the whole screen area and does not display window decorations, such as a title bar.
По умолчанию, это свойство равно false.
Функции доступа:
See also windowState(), minimized, and maximized.
Это свойство содержит геометрию виджета относительно его родителя, исключая оконную рамку.
When changing the geometry, the widget, if visible, receives a move event (moveEvent()) and/or a resize event (resizeEvent()) immediately. Если виджет в данный момент невидим, он гарантированно получит соответствующие события перед тем, как станет видимым.
The size component is adjusted if it lies outside the range defined by minimumSize() and maximumSize().
Warning: Calling setGeometry() inside resizeEvent() or moveEvent() can lead to infinite recursion.
See the Window Geometry documentation for an overview of window geometry.
By default, this property contains a value that depends on the user's platform and screen geometry.
Функции доступа:
See also frameGeometry(), rect(), move(), resize(), moveEvent(), resizeEvent(), minimumSize(), and maximumSize().
Это свойство содержит высоту виджета, исключая оконную рамку.
See the Window Geometry documentation for an overview of window geometry.
Note: Do not use this function to find the height of a screen on a multiple screen desktop. Read this note for details.
By default, this property contains a value that depends on the user's platform and screen geometry.
Функции доступа:
See also geometry, width, and size.
Это свойство показываеет, является ли окно виджета активным.
Активное окно это окно, которое содержит виджет, имеющий фокус ввода склавиатуры (окно также может иметь фокус, даже если не имеет никаких виджетов или виджетов, получающих фокус ввода с клавиатуры).
When popup windows are visible, this property is true for both the active window and for the popup.
По умолчанию, это свойство равно false.
Функции доступа:
See also activateWindow() and QApplication::activeWindow().
Это свойство содержит направление компоновки для этого виджета.
By default, this property is set to Qt::LeftToRight.
Функции доступа:
See also QApplication::layoutDirection.
Это свойство содержит локаль виджета.
До тех пор, пока не установленна специальная локаль для виджета, здесь хранится либо локаль родительского виджета, либо (если виджет является виджетом верхнего уровня) локаль, установленная по умолчанию.
Если виджет отображает дату или числа, они будут отформатированы соответственно с использованием локали виджета.
Это свойство было введено в Qt 4.3.
Функции доступа:
See also QLocale and QLocale::setDefault().
Это свойство показывает, распахнут ли виджет в максимальный размер.
Это свойство актуально только для окон.
Note: Due to limitations on some window systems, this does not always report the expected results (e.g., if the user on X11 maximizes the window via the window manager, Qt has no way of distinguishing this from any other resize). Ожидается, что протокол оконного менеджера со временем улучшится.
По умолчанию, это свойство равно false.
Функции доступа:
See also windowState(), showMaximized(), visible, show(), hide(), showNormal(), and minimized.
This property holds the widget's maximum height in pixels.
This property corresponds to the height held by the maximumSize property.
By default, this property contains a value of 16777215.
Note: The definition of the QWIDGETSIZE_MAX macro limits the maximum size of widgets.
Функции доступа:
See also maximumSize and maximumWidth.
This property holds the widget's maximum size in pixels.
Виджет не может быть растянут больше, чем его максимальный размер.
By default, this property contains a size in which both width and height have values of 16777215.
Note: The definition of the QWIDGETSIZE_MAX macro limits the maximum size of widgets.
Функции доступа:
See also maximumWidth, maximumHeight, minimumSize, and sizeIncrement.
This property holds the widget's maximum width in pixels.
This property corresponds to the width held by the maximumSize property.
By default, this property contains a value of 16777215.
Note: The definition of the QWIDGETSIZE_MAX macro limits the maximum size of widgets.
Функции доступа:
See also maximumSize and maximumHeight.
Это свойство показывает, свернут ли виджет (спрятан под иконку).
Это свойство актуально только для окон.
По умолчанию, это свойство равно false.
Функции доступа:
See also showMinimized(), visible, show(), hide(), showNormal(), and maximized.
This property holds the widget's minimum height in pixels.
This property corresponds to the height held by the minimumSize property.
By default, this property has a value of 0.
Функции доступа:
See also minimumSize and minimumWidth.
Это свойство определяет минимальные размеры виджета.
Виджет не может быть сжат меньше, чем позволяют его минимальные размеры. Виджет будет насильно приведен к минимальному размеру, если его текущие размеры окажутся меньше минимальных.
The minimum size set by this function will override the minimum size defined by QLayout. In order to unset the minimum size, use a value of QSize(0, 0).
По умолчанию, это свойство содержит размер с нулевой шириной и высотой.
Функции доступа:
See also minimumWidth, minimumHeight, maximumSize, and sizeIncrement.
Это свойство определяет рекомендованный минимальный размер для виджета.
Если в свойстве указано неверное значение, то никакого минимального размера не рекомендуется.
По умолчанию функция minimumSizeHint() возвращает неверный размер, если виджет не заключен в компановщик, в противном случае возвращает минимальный размер, заданный компановщиком. У большинства встроенных виджетов перегружена функция minimumSizeHint().
QLayout will never resize a widget to a size smaller than the minimum size hint unless minimumSize() is set or the size policy is set to QSizePolicy::Ignore. If minimumSize() is set, the minimum size hint will be ignored.
Функции доступа:
See also QSize::isValid(), resize(), setMinimumSize(), and sizePolicy().
This property holds the widget's minimum width in pixels.
This property corresponds to the width held by the minimumSize property.
By default, this property has a value of 0.
Функции доступа:
See also minimumSize and minimumHeight.
Это свойство определяет, является ли виджет модальным.
Это свойство актуально только для окон. Модальный виджет не допускает любую попытку передать ввод виджетам других окон.
По умолчанию, это свойство равно false.
Функции доступа:
See also isWindow(), windowModality, and QDialog.
Это свойство указывает, разрешено ли перемещение мышки для этого виджета.
Если перемещение мышки запрещено (по умолчанию), виджет получает события о перемещении мышки только тогда, когда нажата покрайней мере одна кнопка в время движения мышки.
Если перемещение мышки разрешено, виджет получает события о перемещении мышки, даже если не нажата ни одна кнопка.
Функции доступа:
See also mouseMoveEvent().
This property holds the geometry of the widget as it will appear when shown as a normal (not maximized or full screen) top-level widget.
For child widgets this property always holds an empty rectangle.
By default, this property contains an empty rectangle.
Функции доступа:
See also QWidget::windowState() and QWidget::geometry.
Это свойство содержит палитру виджета.
As long as no special palette has been set, this is either a special palette for the widget class, the parent's palette, or (if this widget is a top level widget), the default application palette.
The palette's background color will only have an effect on the appearance of the widget if the autoFillBackground property is set.
There are two types of styles in Qt:
Changing this property on a widget with a pixmap based style will usually not result in a visual change on that widget. Refer to our Knowledge Base article here for more information.
Warning: Do not use this function in conjunction with Qt Style Sheets. Когда используются таблицы стилей, палитра виджета может устанорвить "цвет (color)", " цвет фона (background-color)", "цвет выделения (selection-color)", "цвет выделенного фона (selection-background-color)" и "дополнительный цвет фона (alternate-background-color)".
Функции доступа:
See also QApplication::palette().
Это свойство содержит позицию виджета внутри родительского виджета.
Если виджет является окном, это его позиция на рабочем столе, включая его рамку.
When changing the position, the widget, if visible, receives a move event (moveEvent()) immediately. Если виджет в данный момент не видим, он гарантированно получит это событие перед тем, как станет видимым.
By default, this property contains a position that refers to the origin.
Warning: Calling move() or setGeometry() inside moveEvent() can lead to infinite recursion.
See the Window Geometry documentation for an overview of window geometry.
Функции доступа:
See also frameGeometry, size, x(), and y().
Это свойство содержит внутреннюю геометрию виджета, исключая рамку
The rect property equals QRect(0, 0, width(), height()).
See the Window Geometry documentation for an overview of window geometry.
By default, this property contains a value that depends on the user's platform and screen geometry.
Функции доступа:
See also size.
Свойство содержит размеры виджета исключая оконную рамку.
If the widget is visible when it is being resized, it receives a resize event (resizeEvent()) immediately. Если виджет в данный момент не видим, он гарантированно получит это событие перед тем, как станет видимым.
The size is adjusted if it lies outside the range defined by minimumSize() and maximumSize().
By default, this property contains a value that depends on the user's platform and screen geometry.
Warning: Calling resize() or setGeometry() inside resizeEvent() can lead to infinite recursion.
Note: Setting the size to QSize(0, 0) will cause the widget to not appear on screen. Это также верно для окон.
Функции доступа:
See also pos, geometry, minimumSize, maximumSize, and resizeEvent().
Это свойство определяет рекомендованный размер для виджета.
Если в свойстве указано неверное значение, то никакого размера не рекомендуется.
По умолчанию функция sizeHint() возвращает неверный размер, если виджет не заключен в компановщик, в противном случае возвращает размер, заданный компановщиком.
Функции доступа:
See also QSize::isValid(), minimumSizeHint(), sizePolicy(), setMinimumSize(), and updateGeometry().
Это свойство определяет шаг изменения размера виджета.
When the user resizes the window, the size will move in steps of sizeIncrement().width() pixels horizontally and sizeIncrement.height() pixels vertically, with baseSize() as the basis. Preferred widget sizes are for non-negative integers i and j:
width = baseSize().width() + i * sizeIncrement().width(); height = baseSize().height() + j * sizeIncrement().height();
Заметим, что хотя вы можете устанавливать шаг изменения размера для всех виджетов, эффект ощутим только для окон.
По умолчанию, это свойство содержит размер с нулевой шириной и высотой.
Warning: The size increment has no effect under Windows, and may be disregarded by the window manager on X11.
Функции доступа:
See also size, minimumSize, and maximumSize.
Это свойство определяет поведение виджета при применении компановщика.
If there is a QLayout that manages this widget's children, the size policy specified by that layout is used. If there is no such QLayout, the result of this function is used.
The default policy is Preferred/Preferred, which means that the widget can be freely resized, but prefers to be the size sizeHint() returns. Воджеты типакнопок устанавливают политику размеров таким образом, чтобы свободно изменять размер по горизонтали и иметь фиксированный размер по вертикали. The same applies to lineedit controls (such as QLineEdit, QSpinBox or an editable QComboBox) and other horizontally orientated widgets (such as QProgressBar). QToolButton's are normally square, so they allow growth in both directions. Widgets that support different directions (such as QSlider, QScrollBar or QHeader) specify stretching in the respective direction only. Widgets that can provide scroll bars (usually subclasses of QScrollArea) tend to specify that they can use additional space, and that they can make do with less than sizeHint().
Функции доступа:
See also sizeHint(), QLayout, QSizePolicy, and updateGeometry().
Это свойство определяет подсказку в строке состояния.
По умолчанию, это свойство содержит пустую строку.
Функции доступа:
See also toolTip and whatsThis.
Это свойство определяет таблицу стилей для виджета.
The style sheet contains a textual description of customizations to the widget's style, as described in the Qt Style Sheets document.
Note: Qt style sheets are currently not supported for QMacStyle (the default style on Mac OS X). Мы планируем вернуться к этому в одном из следующих релизов.
Это свойство было введено в Qt 4.2.
Функции доступа:
See also setStyle(), QApplication::styleSheet, and Qt Style Sheets.
Это свойство определяет контекстную подсказку виджета.
Заметим, что по умолчанию контекстная подсказка показывается толко для виджетов, которые являются дитьми активного окна. You can change this behavior by setting the attribute Qt::WA_AlwaysShowToolTips on the window, not on the widget with the tooltip.
If you want to control a tooltip's behavior, you can intercept the event() function and catch the QEvent::ToolTip event (e.g., if you want to customize the area for which the tooltip should be shown).
По умолчанию, это свойство содержит пустую строку.
Функции доступа:
See also QToolTip, statusTip, and whatsThis.
Это свойство определяет возможность обновления (перерисовки) виджета.
Виджет, которому разрешено обновляться, получает событие перерисовки и имеет системный фон; у виджетов, которым не разрешено обновление, этого нет. This also implies that calling update() and repaint() has no effect if updates are disabled.
По умолчанию это свойство равно true.
setUpdatesEnabled() обычно используют для заперщения изменений на короткий промежуток времени, чтобы избежать мерцания экрана во время больших изменений. Обычно, в Qt виджеты не генерируют мерцания экрана, но в X11 сервер может очищать область экрана, когда виджет скрывается перед тем, как его переместят к другим виджетам. Запрет обновления (перерисовки) решает эту проблему.
Пример:
setUpdatesEnabled(false); bigVisualChanges(); setUpdatesEnabled(true);
Запрет обновления у виджета означает запрет обновления у всех его детей. Разрешение, соответственно, разрешает обновление всем детям, исключая те, которые явно запрещены. Re-enabling updates implicitly calls update() on the widget.
Функции доступа:
See also paintEvent().
Это свойство показывет, является ли виджет видимым или нет.
Calling setVisible(true) or show() sets the widget to visible status if all its parent widgets up to the window are visible. Если один из предков виджета невидим, виджет не может стать видимым, пока все его предки не станут видимы. Если позиция виджета изменилась, Qt гарантирует, что виджет получит события об изменении размеров и перемещении до того, как будет отображен. If the widget has not been resized yet, Qt will adjust the widget's size to a useful default using adjustSize().
Calling setVisible(false) or hide() hides a widget explicitly. Явно погашенный виджет не становится видимым, даже если все его предки стали водимыми, до тех пор пока вы датите команду отобразить его.
Виджет получает события отображения и скрытия, когда меняется его признак видимости. В промежутке между событиями гашения и отображения процессору нет необходимости тратить время на подготовку и отображение информации для пользователя. Например, видео-приложение может просто остановить генерирование новых кадров.
Виджет, который скрыт под другим окном на экране считается видимым. То же относится к окнам, свернутым под иконку, и окнам, которые существуют на других виртуальных рабочих столах (для тех платфом, которые поддреживают концепцию нескольких столов). Виджет получает спонтанные события отображения и гашения, когда его состояние отображения меняется оконной системой, например, спонтанные события гашения приходят, когда пользователь сворачивает окно, и спонтанные события отображения приходят, когда окно опять разворачивается.
Вам почти никогда не понадобится перегружать функцию setVisible(). If you need to change some settings before a widget is shown, use showEvent() instead. If you need to do some delayed initialization use the Polish event delivered to the event() function.
Функции доступа:
See also show(), hide(), isHidden(), isVisibleTo(), isMinimized(), showEvent(), and hideEvent().
Это свойство определяет текст подсказки What's This для виджета.
По умолчанию, это свойство содержит пустую строку.
Функции доступа:
See also QWhatsThis, QWidget::toolTip, and QWidget::statusTip.
Это свойство задаёт ширину виджета, исключая оконную рамку.
See the Window Geometry documentation for an overview of window geometry.
Note: Do not use this function to find the width of a screen on a multiple screen desktop. Read this note for details.
By default, this property contains a value that depends on the user's platform and screen geometry.
Функции доступа:
See also geometry, height, and size.
Это свойство определяет путь к файлу, ассоциирующемуся с виджетом.
Это свойство актуально только для окон. Оно ассоциирует путь к файлу с окном. If you set the file path, but have not set the window title, Qt sets the window title to contain a string created using the following components.
On Mac OS X:
On Windows and X11:
If the window title is set at any point, then the window title takes precedence and will be shown instead of the file path string.
Additionally, on Mac OS X, this has an added benefit that it sets the proxy icon for the window, assuming that the file path exists.
If no file path is set, this property contains an empty string.
По умолчанию, это свойство содержит пустую строку.
Это свойство было введено в Qt 4.4.
Функции доступа:
See also windowTitle and windowIcon.
Window flags are a combination of a type (e.g. Qt::Dialog) and zero or more hints to the window system (e.g. Qt::FramelessWindowHint).
If the widget had type Qt::Widget or Qt::SubWindow and becomes a window (Qt::Window, Qt::Dialog, etc.), it is put at position (0, 0) on the desktop. If the widget is a window and becomes a Qt::Widget or Qt::SubWindow, it is put at position (0, 0) relative to its parent widget.
Note: This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again..
Функции доступа:
See also windowType() and Window Flags Example.
Это свойство определяет иконку окна.
Это свойство актуально только для окон. If no icon has been set, windowIcon() returns the application icon (QApplication::windowIcon()).
Функции доступа:
See also windowIconText and windowTitle.
Это свойство определяет текст для иконки.
Это свойство актуально только для окон. Если текст иконки не установлен, эта функция вернет пустую строку.
Функции доступа:
See also windowIcon and windowTitle.
Это свойство определяет, блокируется ли окно модальным виджетом.
Это свойство актуально только для окон. Модальный виджет лишает виджеты других окон возможности ввода. Значение этого свойства контролирует блокировку окна, когда виджет видим. Changing this property while the window is visible has no effect; you must hide() the widget first, then show() it again.
By default, this property is Qt::NonModal.
Это свойство было введено в Qt 4.1.
Функции доступа:
See also isWindow(), QWidget::modal, and QDialog.
Это свойство определяет будут ли сохраняться изменения, сделанные в документе, открытом в окне.
Модифицированное окно (a modified window) это окно, содержимое которого было изменено, но изменения не сохранены на диск. Этот флаг имеет различный эффект в зависимости от платформы. В Mac OS X кнопка закрытия будет иметь изменённый вид; в других платформах Рядом с заголовком окна будет стоять символ '*' (звездочка).
Заголовок окна должен содержать символы-заполнители "[*]", которые указывают, в каком месте должна отображаться звездочка'*'. Обычно, она отображается справа после имени файла (например, "document1.txt[*] - Text Editor"). Если окно не модифицировалось для модификаций, символы-заполнители просто удаляются.
Note that if a widget is set as modified, all its ancestors will also be set as modified. However, if you call setWindowModified(false) on a widget, this will not propagate to its parent because other children of the parent might have been modified.
Функции доступа:
See also windowTitle, Application Example, SDI Example, and MDI Example.
Это свойство определяет уровень непрозрачности для окна.
Допустимые значения непрозрачности от 1.0 (совершенно непрозначно) до 0.0 (совершенно прозрачно).
По умолчанию это свойство имеет значение 1.0.
Эта особенность появилась в Embedded Linux, Mac OS X, X11 платформах, которые поддерживают композитное расширение (Composite extension), и Windows 2000 и поздние версии.
Это свойство не поддерживается в Windows CE.
Заметим, что под X11 вам необходимо запустить композитный менеджер (composite manager), и вах оконный менеджер X11 должен поддерживать специфичный атом _NET_WM_WINDOW_OPACITY.
Warning: Changing this property from opaque to transparent might issue a paint event that needs to be processed before the window is displayed correctly. This affects mainly the use of QPixmap::grabWindow(). Также заметим, что полупрозрачные окна обновляются или меняют размер заметно медленнее, чем непрозрачные.
Функции доступа:
See also setMask().
Это свойство содерзит заголовок окна (caption).
Это свойство нужно только для виджетов верхнего уровня, таких как окна и диалоги. If no caption has been set, the title is based of the windowFilePath. Если и это свойство не установлено, то заголовок будет пустой строкой.
If you use the windowModified mechanism, the window title must contain a "[*]" placeholder, which indicates where the '*' should appear. Обычно, она отображается справа после имени файла (например, "document1.txt[*] - Text Editor"). If the windowModified property is false (the default), the placeholder is simply removed.
Функции доступа:
See also windowIcon, windowIconText, windowModified, and windowFilePath.
Это свойство содержит координату x виджета относительно родителя, включая любую оконную рамку.
See the Window Geometry documentation for an overview of window geometry.
By default, this property has a value of 0.
Функции доступа:
See also frameGeometry, y, and pos.
Это свойство содержит координату y виджета относительно родителя, включая любую оконную рамку.
See the Window Geometry documentation for an overview of window geometry.
By default, this property has a value of 0.
Функции доступа:
See also frameGeometry, x, and pos.
Constructs a widget which is a child of parent, with widget flags set to f.
If parent is 0, the new widget becomes a window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when its parent is deleted.
The widget flags argument, f, is normally 0, but it can be set to customize the frame of a window (i.e. parent must be 0). To customize the frame, use a value composed from the bitwise OR of any of the window flags.
Если вы добавляете дочерний виджет на уже видимый виджет, вы должны явно сделать дочерний виджет видимым.
Заметим, что в версии Qt для X11 могут быть возможны не все комбинации флагов стилей. Это происходит потому, что в X11 Qt может только спросить менеджер окон, а уже менеджер меняет установки приложения. В Windows Qt может установить флаг. какой вы пожелаете.
See also windowFlags.
Разрушает виджет.
Сперва разрушаются все дети виджета. Приложение завершается, если это был главный виджет.
This event handler is called with the given event whenever the widget's actions are changed.
See also addAction(), insertAction(), removeAction(), actions(), and QActionEvent.
Возвращает (возможно пустой) список действий этого виджета.
See also contextMenuPolicy, insertAction(), and removeAction().
Sets the top-level widget containing this widget to be the active window.
An active window is a visible top-level window that has the keyboard input focus.
This function performs the same operation as clicking the mouse on the title bar of a top-level window. On X11, the result depends on the Window Manager. If you want to ensure that the window is stacked on top as well you should also call raise(). Note that the window must be visible, otherwise activateWindow() has no effect.
On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window. It will change the color of the taskbar entry to indicate that the window has changed in some way. This is because Microsoft do not allow an application to interrupt what the user is currently doing in another application.
See also isActiveWindow(), window(), and show().
Добавляет действие action в список действий этого виджета.
All QWidgets have a list of QActions, however they can be represented graphically in many different ways. Обычное использование списка QAction (возвращаемого actions()) это создать контекстное меню QMenu.
A QWidget should only have one of each action and adding an action it already has will not cause the same action to be in the widget twice.
See also removeAction(), insertAction(), actions(), and QMenu.
Добавляет действия actions в список действий этого виджета.
See also removeAction(), QMenu, and addAction().
Устанавливает оптимальные резмеры виджета в зависимости от его содержимого.
Uses sizeHint() if valid (i.e if the size hint's width and height are >= 0); otherwise sets the size to the children rectangle that covers all child widgets (the union of all child widget rectangles).
For windows, the screen size is also taken into account, and if the sizeHint() is less than (200, 100) and the size policy is expanding, the window is made to be at least (200, 100).
See also sizeHint() and childrenRect().
Возвращает роль для фона виджета.
The background role defines the brush from the widget's palette that is used to render the background.
Если явно не установлена роль для фона, виджет наследует её от родителя.
See also setBackgroundRole() and foregroundRole().
Этот обработчик событий может быть переопределён чтобы обрабатывать изменения состояния.
The state being changed in this event can be retrieved through event event.
Change events include: QEvent::ToolBarChange, QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange, QEvent::StyleChange, QEvent::PaletteChange, QEvent::WindowTitleChange, QEvent::IconTextChange, QEvent::ModifiedChange, QEvent::MouseTrackingChange, QEvent::ParentChange, QEvent::WindowStateChange, QEvent::LanguageChange, QEvent::LocaleChange, QEvent::LayoutDirectionChange.
Returns the visible child widget at the position (x, y) in the widget's coordinate system. Если в указанной позиции детей виджета нет, функция вернёт 0.
Это перегруженная функция, предоставленная для удобства.
Returns the visible child widget at point p in the widget's own coordinate system.
Отдаёт фокус ввода с клавиатуры.
If the widget has active focus, a focus out event is sent to this widget to tell it that it is about to lose the focus.
This widget must enable focus setting in order to get the keyboard input focus, i.e. it must call setFocusPolicy().
See also hasFocus(), setFocus(), focusInEvent(), focusOutEvent(), setFocusPolicy(), and QApplication::focusWidget().
Removes any mask set by setMask().
See also setMask().
Закрывает этот виджет. Возвращает true, если виджет был закрыт, в противном случае возвращает false.
First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event.
If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. На событие закрытия не влияет, является ли виджет видимым или нет.
The QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. По умолчанию этот атрибут установлен для всех виджетов, за исключением таких окон, как окна-заставки, окна инструментов, выпадающие меню.
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.
По умолчанию событие разрешено и виджет должен закрыться. Вы можете перегрузить эту функцию, чтобы виджет мог иначе отреагировать на запрос о закрытии окна. For example, you can prevent the window from closing by calling ignore() on all events.
Приложения, имеющие главное окно , обычно используют перегруженный обработчик для проверки, вся ли пользовательская работа сохранена и запроса подтверждения перед закрытием. For example, the Application Example uses a helper function to determine whether or not to close the window:
void MainWindow::closeEvent(QCloseEvent *event)
{
if (maybeSave()) {
writeSettings();
event->accept();
} else {
event->ignore();
}
}
See also event(), hide(), close(), QCloseEvent, and Application Example.
Возвращает область внутри границ виджета.
Смотрите также setContentsMargins() и getContentsMargins().
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.
По умолчанию события вызова контекстного меню игнорируются. See the QContextMenuEvent documentation for more details.
See also event(), QContextMenuEvent, and customContextMenuRequested().
Creates a new widget window if window is 0, otherwise sets the widget's window to window.
Initializes the window (sets the geometry etc.) if initializeWindow is true. If initializeWindow is false, no initialization is performed. This parameter only makes sense if window is a valid window.
Destroys the old window if destroyOldWindow is true. If destroyOldWindow is false, you are responsible for destroying the window yourself (using platform native code).
The QWidget constructor calls create(0,true,true) to create a window for this widget.
This signal is emitted when the widget's contextMenuPolicy is Qt::CustomContextMenu, and the user has requested a context menu on the widget. The position pos is the position of the context menu event that the widget receives. Normally this is in widget coordinates. The exception to this rule is QAbstractScrollArea and its subclasses that map the context menu event to coordinates of the viewport() .
See also mapToGlobal(), QMenu, and contextMenuPolicy.
Frees up window system resources. Destroys the widget window if destroyWindow is true.
destroy() calls itself recursively for all the child widgets, passing destroySubWindows for the destroyWindow parameter. To have more control over destruction of subwidgets, destroy subwidgets selectively first.
This function is usually called from the QWidget destructor.
This event handler is called when a drag is in progress and the mouse enters this widget. The event is passed in the event parameter.
If the event is ignored, the widget won't receive any drag move events.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QDrag and QDragEnterEvent.
This event handler is called when a drag is in progress and the mouse leaves this widget. The event is passed in the event parameter.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QDrag and QDragLeaveEvent.
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. The event is passed in the event parameter.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QDrag and QDragMoveEvent.
This event handler is called when the drag is dropped on this widget. The event is passed in the event parameter.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QDrag and QDropEvent.
Returns the effective window system identifier of the widget, i.e. the native parent's window system identifier.
Note: We recommend that you do not store this value as it is likely to change during run-time.
Эта функция была введена в Qt 4.4.
See also nativeParentWidget().
Ensures that the widget has been polished by QStyle (i.e., has a proper font and palette).
QWidget calls this function after it has been fully constructed but before it is shown the very first time. You can call this function if you want to ensure that the widget is polished before doing an operation, e.g., the correct font size might be needed in the widget's sizeHint() reimplementation. Note that this function is called from the default implementation of sizeHint().
Polishing is useful for final initialization that must happen after all constructors (from base classes as well as from subclasses) have been called.
If you need to change some settings when a widget is polished, reimplement event() and handle the QEvent::Polish event type.
Note: The function is declared const so that it can be called from other const functions (e.g., sizeHint()).
Смотрите также event().
This event handler can be reimplemented in a subclass to receive widget enter events which are passed in the event parameter.
An event is sent to the widget when the mouse cursor enters the widget.
See also leaveEvent(), mouseMoveEvent(), and event().
This is the main event handler; it handles event event. You can reimplement this function in a subclass, but we recommend using one of the specialized event handlers instead.
Key press and release events are treated differently from other events. event() checks for Tab and Shift+Tab and tries to move the focus appropriately. If there is no widget to move the focus to (or the key press is not Tab or Shift+Tab), event() calls keyPressEvent().
Mouse and tablet event handling is also slightly special: only when the widget is enabled, event() will call the specialized handlers such as mousePressEvent(); otherwise it will discard the event.
This function returns true if the event was recognized, otherwise it returns false. If the recognized event was accepted (see QEvent::accepted), any further processing such as event propagation to the parent widget stops.
Переопределено из QObject.
See also closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(), keyPressEvent(), keyReleaseEvent(), leaveEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(), mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(), QObject::event(), and QObject::timerEvent().
Returns a pointer to the widget with window identifer/handle id.
The window identifier type depends on the underlying window system, see qwindowdefs.h for the actual definition. If there is no widget with this identifier, 0 is returned.
This event handler can be reimplemented in a subclass to receive keyboard focus events (focus received) for the widget. The event is passed in the event parameter
A widget normally must setFocusPolicy() to something other than Qt::NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.)
The default implementation updates the widget (except for windows that do not specify a focusPolicy()).
See also focusOutEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), and QFocusEvent.
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.
See also focusPreviousChild().
Finds a new widget to give the keyboard focus to, as appropriate for Tab and Shift+Tab, and returns true if it can find a new widget, or false if it can't.
If next is true, this function searches forward, if next is false, it searches backward.
Sometimes, you will want to reimplement this function. For example, a web browser might reimplement it to move its "current active link" forward or backward, and call focusNextPrevChild() only when it reaches the last or first link on the "page".
Дочерние виджеты вызывают focusNextPrevChild() своих родителей, но только окно, содержащее дочерние виджеты, решает куда перенаправить фокус. By reimplementing this function for an object, you thus gain control of focus traversal for all child widgets.
See also focusNextChild() and focusPreviousChild().
This event handler can be reimplemented in a subclass to receive keyboard focus events (focus lost) for the widget. The events is passed in the event parameter.
A widget normally must setFocusPolicy() to something other than Qt::NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.)
The default implementation updates the widget (except for windows that do not specify a focusPolicy()).
See also focusInEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), and QFocusEvent.
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.
See also focusNextChild().
Returns the focus proxy, or 0 if there is no focus proxy.
See also setFocusProxy().
Returns the last child of this widget that setFocus had been called on. For top level widgets this is the widget that will get focus in case this window gets activated
This is not the same as QApplication::focusWidget(), which returns the focus widget in the currently active window.
Returns the font info for the widget's current font. Equivalent to QFontInto(widget->font()).
See also font(), fontMetrics(), and setFont().
Returns the font metrics for the widget's current font. Equivalent to QFontMetrics(widget->font()).
See also font(), fontInfo(), and setFont().
Returns the foreground role.
The foreground role defines the color from the widget's palette that is used to draw the foreground.
If no explicit foreground role is set, the function returns a role that contrasts with the background role.
See also setForegroundRole() and backgroundRole().
Returns the widget's contents margins for left, top, right, and bottom.
See also setContentsMargins() and contentsRect().
Returns the window system handle of the widget, for low-level access. Using this function is not portable.
An HDC acquired with getDC() has to be released with releaseDC().
Warning: Using this function is not portable.
Получает ввод клавиатуры.
This widget receives all keyboard events until releaseKeyboard() is called; other widgets get no keyboard events at all. Mouse events are not affected. Use grabMouse() if you want to grab that.
The focus widget is not affected, except that it doesn't receive any keyboard events. setFocus() moves the focus as usual, but the new focus widget receives keyboard events only after releaseKeyboard() is called.
If a different widget is currently grabbing keyboard input, that widget's grab is released first.
See also releaseKeyboard(), grabMouse(), releaseMouse(), and focusWidget().
Получает ввод мыши.
This widget receives all mouse events until releaseMouse() is called; other widgets get no mouse events at all. События клавиатуры не затрагиваются. Use grabKeyboard() if you want to grab that.
Warning: Bugs in mouse-grabbing applications very often lock the terminal. Use this function with extreme caution, and consider using the -nograb command line option while debugging.
It is almost never necessary to grab the mouse when using Qt, as Qt grabs and releases it sensibly. In particular, Qt grabs the mouse when a mouse button is pressed and keeps it until the last button is released.
Note that only visible widgets can grab mouse input. If isVisible() returns false for a widget, that widget cannot call grabMouse().
See also releaseMouse(), grabKeyboard(), releaseKeyboard(), and grabKeyboard().
Это перегруженная функция, предоставленная для удобства.
Grabs the mouse input and changes the cursor shape.
The cursor will assume shape cursor (for as long as the mouse focus is grabbed) and this widget will be the only one to receive mouse events until releaseMouse() is called().
Warning: Grabbing the mouse might lock the terminal.
See also releaseMouse(), grabKeyboard(), releaseKeyboard(), and setCursor().
Adds a shortcut to Qt's shortcut system that watches for the given key sequence in the given context. Если context это Qt::ApplicationShortcut, то комбинация горячих клавиш применяется ко всему приложению. В противном случае, она либо локальна для этого виджета, Qt::WidgetShortcut, либо для самого окна, Qt::WindowShortcut.
If the same key sequence has been grabbed by several widgets, when the key sequence occurs a QEvent::Shortcut event is sent to all the widgets to which it applies in a non-deterministic order, but with the ``ambiguous'' flag set to true.
Предупреждение: Обычно вы не должны использовать эту функцию; вместо этого создайте QAction с последовательностью горячих клавиш которая вам нужна (если вы также хотите эквивалентный пункт меню и панель инструментов), или создайте QShortcut если вам нужна только последовательность клавиш. Оба QAction и QShortcut обрабатывают все отфильтрованные для вас события и предоставляют сигналы, которые срабатывают когда пользователь вводит последовательность клавиш, что намного проще чем эта низкоуровневая функция.
See also releaseShortcut() and setShortcutEnabled().
Returns true if this widget currently has edit focus; otherwise false.
This feature is only available in Qt for Embedded Linux.
See also setEditFocus() and QApplication::keypadNavigationEnabled().
Returns the preferred height for this widget, given the width w.
If this widget has a layout, the default implementation returns the layout's preferred height. if there is no layout, the default implementation returns -1 indicating that the preferred height does not depend on the width.
Hides the widget. This function is equivalent to setVisible(false).
Note: If you are working with QDialog or its subclasses and you invoke the show() function after this function, the dialog will be displayed in its original position.
See also hideEvent(), isHidden(), show(), setVisible(), isVisible(), and close().
This event handler can be reimplemented in a subclass to receive widget hide events. The event is passed in the event parameter.
Hide events are sent to widgets immediately after they have been hidden.
Note: A widget receives spontaneous show and hide events when its mapping status is changed by the window system, e.g. a spontaneous hide event when the user minimizes the window, and a spontaneous show event when the window is restored again. After receiving a spontaneous hide event, a widget is still considered visible in the sense of isVisible().
See also visible, event(), and QHideEvent.
This function returns the QInputContext for this widget. By default the input context is inherited from the widgets parent. For toplevels it is inherited from QApplication.
You can override this and set a special input context for this widget by using the setInputContext() method.
See also setInputContext().
This event handler, for event event, can be reimplemented in a subclass to receive Input Method composition events. This handler is called when the state of the input method changes.
Note that when creating custom text editing widgets, the Qt::WA_InputMethodEnabled window attribute must be set explicitly (using the setAttribute() function) in order to receive input method events.
The default implementation calls event->ignore(), which rejects the Input Method event. See the QInputMethodEvent documentation for more details.
See also event() and QInputMethodEvent.
This method is only relevant for input widgets. It is used by the input method to query a set of properties of the widget to be able to support complex input method operations as support for surrounding text and reconversions.
query указывает какое свойство запрашивается.
Смотрите также inputMethodEvent(), QInputMethodEvent и QInputContext.
Вставляет действие action в список действий этого виджета перед действием before. Эта функция добавит действие если before равно 0 или before не действительное действие для этого виджета.
A QWidget should only have one of each action.
See also removeAction(), addAction(), QMenu, contextMenuPolicy, and actions().
Вставляет действия actions в список действий этого виджета перед действием before. Эта функция добавит действие если before равно 0 или before не действительное действие для этого виджета.
A QWidget can have at most one of each action.
See also removeAction(), QMenu, insertAction(), and contextMenuPolicy.
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.
Returns true if this widget would become enabled if ancestor is enabled; otherwise returns false.
This is the case if neither the widget itself nor every parent up to but excluding ancestor has been explicitly disabled.
isEnabledTo(0) is equivalent to isEnabled().
See also setEnabled() and enabled.
Returns true if the widget is hidden, otherwise returns false.
A hidden widget will only become visible when show() is called on it. It will not be automatically shown when the parent is shown.
To check visiblity, use !isVisible() instead (notice the exclamation mark).
isHidden() implies !isVisible(), but a widget can be not visible and not hidden at the same time. This is the case for widgets that are children of widgets that are not visible.
Widgets are hidden if they were created as independent windows or as children of visible widgets, or if hide() or setVisible(false) was called.
Returns true if this widget would become visible if ancestor is shown; otherwise returns false.
The true case occurs if neither the widget itself nor any parent up to but excluding ancestor has been explicitly hidden.
This function will still return true if the widget is obscured by other windows on the screen, but could be physically visible if it or they were to be moved.
isVisibleTo(0) is identical to isVisible().
See also show(), hide(), and isVisible().
Returns true if the widget is an independent window, otherwise returns false.
A window is a widget that isn't visually the child of any other widget and that usually has a frame and a window title.
A window can have a parent widget. It will then be grouped with its parent and deleted when the parent is deleted, minimized when the parent is minimized etc. If supported by the window manager, it will also have a common taskbar entry with its parent.
QDialog and QMainWindow widgets are by default windows, even if a parent widget is specified in the constructor. This behavior is specified by the Qt::Window flag.
See also window(), isModal(), and parentWidget().
This event handler, for event event, can be reimplemented in a subclass to receive key press events for the widget.
A widget must call setFocusPolicy() to accept focus initially and have focus in order to receive a key press event.
If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.
The default implementation closes popup widgets if the user presses Esc. Otherwise the event is ignored, so that the widget's parent can interpret it.
Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent::accept() - just do not call the base class implementation if you act upon the key.
See also keyReleaseEvent(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), QKeyEvent, and Tetrix Example.
This event handler, for event event, can be reimplemented in a subclass to receive key release events for the widget.
A widget must accept focus initially and have focus in order to receive a key release event.
If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.
The default implementation ignores the event, so that the widget's parent can interpret it.
Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent::accept() - just do not call the base class implementation if you act upon the key.
See also keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), and QKeyEvent.
Returns the widget that is currently grabbing the keyboard input.
If no widget in this application is currently grabbing the keyboard, 0 is returned.
See also grabMouse() and mouseGrabber().
Returns the layout manager that is installed on this widget, or 0 if no layout manager is installed.
The layout manager sets the geometry of the widget's children that have been added to the layout.
See also setLayout(), sizePolicy(), and Layout Classes.
This event handler can be reimplemented in a subclass to receive widget leave events which are passed in the event parameter.
A leave event is sent to the widget when the mouse cursor leaves the widget.
See also enterEvent(), mouseMoveEvent(), and event().
Lowers the widget to the bottom of the parent widget's stack.
After this call the widget will be visually behind (and therefore obscured by) any overlapping sibling widgets.
See also raise() and stackUnder().
This special event handler can be reimplemented in a subclass to receive native Macintosh events which are passed from the caller with the event details in the event parameter.
In your reimplementation of this function, if you want to stop the event being handled by Qt, return true. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget.
Warning: This function is not portable.
Warning: This function was not called inside of Qt until Qt 4.4. For compatibility with earlier versions of Qt, consider using QApplication::macEventFilter() instead.
See also QApplication::macEventFilter().
Translates the widget coordinate pos from the coordinate system of parent to this widget's coordinate system. The parent must not be 0 and must be a parent of the calling widget.
See also mapTo(), mapFromParent(), mapFromGlobal(), and underMouse().
Translates the global screen coordinate pos to widget coordinates.
See also mapToGlobal(), mapFrom(), and mapFromParent().
Translates the parent widget coordinate pos to widget coordinates.
Same as mapFromGlobal() if the widget has no parent.
See also mapToParent(), mapFrom(), mapFromGlobal(), and underMouse().
Translates the widget coordinate pos to the coordinate system of parent. The parent must not be 0 and must be a parent of the calling widget.
See also mapFrom(), mapToParent(), mapToGlobal(), and underMouse().
Translates the widget coordinate pos to global screen coordinates. For example, mapToGlobal(QPoint(0,0)) would give the global coordinates of the top-left pixel of the widget.
See also mapFromGlobal(), mapTo(), and mapToParent().
Translates the widget coordinate pos to a coordinate in the parent widget.
Same as mapToGlobal() if the widget has no parent.
See also mapFromParent(), mapTo(), mapToGlobal(), and underMouse().
Returns the mask currently set on a widget. If no mask is set the return value will be an empty region.
See also setMask(), clearMask(), QRegion::isEmpty(), and Shaped Clock Example.
Internal implementation of the virtual QPaintDevice::metric() function.
m is the metric to get.
Reimplemented from QPaintDevice.
This event handler, for event event, can be reimplemented in a subclass to receive mouse double click events for the widget.
The default implementation generates a normal mouse press event.
Note that the widgets gets a mousePressEvent() and a mouseReleaseEvent() before the mouseDoubleClickEvent().
See also mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(), event(), and QMouseEvent.
Returns the widget that is currently grabbing the mouse input.
If no widget in this application is currently grabbing the mouse, 0 is returned.
See also grabMouse() and keyboardGrabber().
This event handler, for event event, can be reimplemented in a subclass to receive mouse move events for the widget.
If mouse tracking is switched off, mouse move events only occur if a mouse button is pressed while the mouse is being moved. If mouse tracking is switched on, mouse move events occur even if no mouse button is pressed.
QMouseEvent::pos() reports the position of the mouse cursor, relative to this widget. For press and release events, the position is usually the same as the position of the last mouse move event, but it might be different if the user's hand shakes. This is a feature of the underlying window system, not Qt.
See also setMouseTracking(), mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), event(), QMouseEvent, and Scribble Example.
This event handler, for event event, can be reimplemented in a subclass to receive mouse press events for the widget.
If you create new widgets in the mousePressEvent() the mouseReleaseEvent() may not end up where you expect, depending on the underlying window system (or X11 window manager), the widgets' location and maybe more.
The default implementation implements the closing of popup widgets when you click outside the window. For other widget types it does nothing.
See also mouseReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), QMouseEvent, and Scribble Example.
This event handler, for event event, can be reimplemented in a subclass to receive mouse release events for the widget.
See also mousePressEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), QMouseEvent, and Scribble Example.
This event handler can be reimplemented in a subclass to receive widget move events which are passed in the event parameter. When the widget receives this event, it is already at the new position.
The old position is accessible through QMoveEvent::oldPos().
See also resizeEvent(), event(), move(), and QMoveEvent.
Returns the native parent for this widget, i.e. the next ancestor widget that has a system identifier, or 0 if it does not have any native parent.
Эта функция была введена в Qt 4.4.
See also effectiveWinId().
Returns the next widget in this widget's focus chain.
Sets the window flags for the widget to flags, without telling the window system.
Warning: Do not call this function unless you really know what you're doing.
See also setWindowFlags().
Returns the widget's paint engine.
Reimplemented from QPaintDevice.
This event handler can be reimplemented in a subclass to receive paint events which are passed in the event parameter.
A paint event is a request to repaint all or part of the widget. It can happen as a result of repaint() or update(), or because the widget was obscured and has now been uncovered, or for 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()). repaint() 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 that you're painting on the widget's background.
The background can be set using setBackgroundRole() and setPalette().
From Qt 4.0, QWidget automatically double-buffers its painting, so there's no need to write double-buffering code in paintEvent() to avoid flicker.
Note: Under X11 it is possible to toggle the global double buffering by calling qt_x11_set_global_double_buffer(). Example usage:
... extern void qt_x11_set_global_double_buffer(bool); qt_x11_set_global_double_buffer(false); ...
Note: In general, one should refrain from calling update() or repaint() inside of 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.
See also event(), repaint(), update(), QPainter, QPixmap, QPaintEvent, and Analog Clock Example.
Returns the parent of this widget, or 0 if it does not have any parent widget.
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.
In your reimplementation of this function, if you want to stop the event being handled by Qt, return true. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget.
Warning: This function is not portable.
See also QApplication::qwsEventFilter().
Raises this widget to the top of the parent widget's stack.
After this call the widget will be visually in front of any overlapping sibling widgets.
Note: When using activateWindow(), you can call this function to ensure that the window is stacked on top.
See also lower() and stackUnder().
Releases the HDC hdc acquired by a previous call to getDC().
Warning: Using this function is not portable.
Освобождает фокус ввода клавиатуры.
See also grabKeyboard(), grabMouse(), and releaseMouse().
Освобождает фокус ввода мыши.
See also grabMouse(), grabKeyboard(), and releaseKeyboard().
Удаляет горячую комбинацию клавиш с указанным id из системы горячих клавиш Qt. Виджет больше не будет получать события QEvent::Shortcut для последовательности событий этой комбинации (если только нет другой комбинации горячих клавиш с такой последовательностью).
Предупреждение: Обычно вам не нужно использовать эту функцию, так как система горячих клавиш Qt удаляет комбинацию горячих клавиш автоматически при уничтожении их родительского виджета. Для обработки комбинаций горячих клавиш лучше использовать QAction или QShortcut, так как они проще в использовании чем низкоуровневая функция. Также заметьте, что это затратная операция.
See also grabShortcut() and setShortcutEnabled().
Удаляет действие action из списка действий этого виджета.
See also insertAction(), actions(), and insertAction().
Renders the sourceRegion of this widget into the target using renderFlags to determine how to render. Rendering starts at targetOffset in the target. Например:
QPixmap pixmap(widget->size()); widget->render(&pixmap);
If sourceRegion is a null region, this function will use QWidget::rect() as the region, i.e. the entire widget.
Note: Make sure to call QPainter::end() for the given target's active painter (if any) before rendering. Например:
QPainter painter(this); ... painter.end(); myWidget->render(this);
Эта функция была введена в Qt 4.3.
Это перегруженная функция, предоставленная для удобства.
Renders the widget into the painter's QPainter::device().
Transformations and settings applied to the painter will be used when rendering.
Note: The painter must be active. On Mac OS X the widget will be rendered into a QPixmap and then drawn by the painter.
See also QPainter::device().
Repaints the widget directly by calling paintEvent() immediately, unless updates are disabled or the widget is hidden.
We suggest only using repaint() if you need an immediate repaint, for example during animation. In almost all circumstances update() is better, as it permits Qt to optimize for speed and minimize flicker.
Warning: If you call repaint() in a function which may itself be called from paintEvent(), you may get infinite recursion. The update() function never causes recursion.
See also update(), paintEvent(), and setUpdatesEnabled().
Это перегруженная функция, предоставленная для удобства.
This version repaints a rectangle (x, y, w, h) inside the widget.
If w is negative, it is replaced with width() - x, and if h is negative, it is replaced width height() - y.
Это перегруженная функция, предоставленная для удобства.
This version repaints a rectangle r inside the widget.
Это перегруженная функция, предоставленная для удобства.
This version repaints a region rgn inside the widget.
This function can be called on the widget that currently has focus to reset the input method operating on it.
See also QInputContext and QInputContext::reset().
This event handler can be reimplemented in a subclass to receive widget resize events which are passed in the event parameter. When resizeEvent() is called, the widget already has its new geometry. The old size is accessible through QResizeEvent::oldSize().
The widget will be erased and receive a paint event immediately after processing the resize event. No drawing need be (or should be) done inside this handler.
See also moveEvent(), event(), resize(), QResizeEvent, paintEvent(), and Scribble Example.
Restores the geometry and state top-level widgets stored in the byte array geometry. Возвращает true, если всё прошло успешно; в противном случае возвращает false.
If the restored geometry is off-screen, it will be modified to be inside the the available screen geometry.
Для восстановления геометрии, сохраненной с использованием QSettings, вы можете использовать примерно такой код:
QSettings settings("MyCompany", "MyApp");
myWidget->restoreGeometry(settings.value("myWidget/geometry").toByteArray());
See the Window Geometry documentation for an overview of geometry issues with windows.
Эта функция была введена в Qt 4.2.
See also saveGeometry() and QSettings.
Saves the current geometry and state for top-level widgets.
Для сохранения геометрии при закрытии окна вы можете реализовать событие закрытия, например, так:
void MyWidget::closeEvent(QCloseEvent *event)
{
QSettings settings("MyCompany", "MyApp");
settings.setValue("geometry", saveGeometry());
QWidget::closeEvent(event);
}
See the Window Geometry documentation for an overview of geometry issues with windows.
Эта функция была введена в Qt 4.2.
See also restoreGeometry().
Scrolls the widget including its children dx pixels to the right and dy downward. Both dx and dy may be negative.
After scrolling, the widgets will receive paint events for the areas that need to be repainted. For widgets that Qt knows to be opaque, this is only the newly exposed parts. For example, if an opaque widget is scrolled 8 pixels to the left, only an 8-pixel wide stripe at the right edge needs updating.
Since widgets propagate the contents of their parents by default, you need to set the autoFillBackground property, or use setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make a widget opaque.
For widgets that use contents propagation, a scroll will cause an update of the entire scroll area.
See also Transparency and Double Buffering.
Это перегруженная функция, предоставленная для удобства.
This version only scrolls r and does not move the children of the widget.
If r is empty or invalid, the result is undefined.
Смотрите также QScrollArea.
Sets the attribute attribute on this widget if on is true; otherwise clears the attribute.
See also testAttribute().
Sets the background role of the widget to role.
The background role defines the brush from the widget's palette that is used to render the background.
If role is QPalette::NoRole, then the widget inherits its parent's background role.
See also backgroundRole() and foregroundRole().
Sets the margins around the contents of the widget to have the sizes left, top, right, and bottom. The margins are used by the layout system, and may be used by subclasses to specify the area to draw in (e.g. excluding the frame).
Changing the margins will trigger a resizeEvent().
See also contentsRect() and getContentsMargins().
Disables widget input events if disable is true; otherwise enables input events.
See the enabled documentation for more information.
See also isEnabledTo(), QKeyEvent, QMouseEvent, and changeEvent().
If enable is true, make this widget have edit focus, in which case Qt::Key_Up and Qt::Key_Down will be delivered to the widget normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to change focus.
This feature is only available in Qt for Embedded Linux.
See also hasEditFocus() and QApplication::keypadNavigationEnabled().
Sets both the minimum and maximum heights of the widget to h without changing the widths. Provided for convenience.
See also sizeHint(), minimumSize(), maximumSize(), and setFixedSize().
Sets both the minimum and maximum sizes of the widget to s, thereby preventing it from ever growing or shrinking.
This will override the default size constraints set by QLayout.
Alternatively, if you want the widget to have a fixed size based on its contents, you can call QLayout::setSizeConstraint(QLayout::SetFixedSize);
See also maximumSize and minimumSize.
Это перегруженная функция, предоставленная для удобства.
Sets the width of the widget to w and the height to h.
Sets both the minimum and maximum width of the widget to w without changing the heights. Provided for convenience.
See also sizeHint(), minimumSize(), maximumSize(), and setFixedSize().
Gives the keyboard input focus to this widget (or its focus proxy) if this widget or one of its parents is the active window. The reason argument will be passed into any focus event sent from this function, it is used to give an explanation of what caused the widget to get focus.
First, a focus out event is sent to the focus widget (if any) to tell it that it is about to lose the focus. Then a focus in event is sent to this widget to tell it that it just received the focus. (Nothing happens if the focus in and focus out widgets are the same.)
setFocus() gives focus to a widget regardless of its focus policy, but does not clear any keyboard grab (see grabKeyboard()).
Be aware that if the widget is hidden, it will not accept focus until it is shown.
Warning: If you call setFocus() in a function which may itself be called from focusOutEvent() or focusInEvent(), you may get an infinite recursion.
setFocusPolicy() QApplication::focusWidget() grabKeyboard() grabMouse(), {Keyboard Focus}
See also hasFocus(), clearFocus(), focusInEvent(), and focusOutEvent().
Это перегруженная функция, предоставленная для удобства.
Gives the keyboard input focus to this widget (or its focus proxy) if this widget or one of its parents is the active window.
Sets the widget's focus proxy to widget w. If w is 0, the function resets this widget to have no focus proxy.
Some widgets can "have focus", but create a child widget, such as QLineEdit, to actually handle the focus. In this case, the widget can set the line edit to be its focus proxy.
setFocusProxy() sets the widget which will actually get focus when "this widget" gets it. If there is a focus proxy, setFocus() and hasFocus() operate on the focus proxy.
See also focusProxy().
Sets the foreground role of the widget to role.
The foreground role defines the color from the widget's palette that is used to draw the foreground.
If role is QPalette::NoRole, the widget uses a foreground role that contrasts with the background role.
See also foregroundRole() and backgroundRole().
Convenience function, equivalent to setVisible(!hidden).
See also isHidden().
This function sets the input context context on this widget.
See also inputContext().
Sets the layout manager for this widget to layout.
If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout.
Пример:
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(lcd);
layout->addWidget(slider);
setLayout(layout);
An alternative to calling this function is to pass this widget to the layout's constructor.
The QWidget will take ownership of layout.
See also layout() and Layout Classes.
Causes only the pixels of the widget for which bitmap has a corresponding 1 bit to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform.
Note that this effect can be slow if the region is particularly complex.
The following code shows how an image with an alpha channel can be used to generate a mask for a widget:
QLabel topLevelLabel;
QPixmap pixmap(":/images/tux.png");
topLevelLabel.setPixmap(pixmap);
topLevelLabel.setMask(pixmap.mask());
The label shown by this code is masked using the image it contains, giving the appearance that an irregularly-shaped image is being drawn directly onto the screen.
Masked widgets receive mouse events only on their visible portions.
See also mask(), clearMask(), windowOpacity(), and Shaped Clock Example.
Это перегруженная функция, предоставленная для удобства.
Causes only the parts of the widget which overlap region to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform.
Note that this effect can be slow if the region is particularly complex.
See also windowOpacity.
Sets the parent of the widget to parent, and resets the window flags. The widget is moved to position (0, 0) in its new parent.
If the new parent widget is in a different window, the reparented widget and its children are appended to the end of the tab chain of the new parent widget, in the same internal order as before. If one of the moved widgets had keyboard focus, setParent() calls clearFocus() for that widget.
If the new parent widget is in the same window as the old parent, setting the parent doesn't change the tab order or keyboard focus.
If the "new" parent widget is the old parent widget, this function does nothing.
Note: The widget becomes invisible as part of changing its parent, even if it was previously visible. You must call show() to make the widget visible again.
Warning: It is very unlikely that you will ever need this function. If you have a widget that changes its content dynamically, it is far easier to use QStackedWidget.
See also setWindowFlags().
Это перегруженная функция, предоставленная для удобства.
This function also takes widget flags, f as an argument.
If enable is true, auto repeat of the shortcut with the given id is enabled; otherwise it is disabled.
Эта функция была введена в Qt 4.2.
See also grabShortcut() and releaseShortcut().
If enable is true, the shortcut with the given id is enabled; otherwise the shortcut is disabled.
Предупреждение: Обычно вам не нужно использовать эту функцию, так как система горячих клавиш Qt включает/отключает комбинацию горячих клавиш автоматически при скрытии/отображении виджета и потери и получения фокуса. Для обработки комбинаций горячих клавиш лучше использовать QAction или QShortcut, так как они проще в использовании чем низкоуровневая функция.
See also grabShortcut() and releaseShortcut().
Sets the widget's GUI style to style. The ownership of the style object is not transferred.
If no style is set, the widget uses the application's style, QApplication::style() instead.
Setting a widget's style has no effect on existing or future child widgets.
Warning: This function is particularly useful for demonstration purposes, where you want to show Qt's styling capabilities. Real applications should avoid it and use one consistent GUI style instead.
Предупреждение: Таблицы стилей Qt в настоящее время не поддерживаются для пользовательских подклассов QStyle. Мы планируем вернуться к этому в одном из следующих релизов.
See also style(), QStyle, QApplication::style(), and QApplication::setStyle().
Перемещает виджет second по кольцу фокуса виджетов таким образом, чтобы при нажатии кнопки Tab фокус клавиатуры переходил от виджета first к виджету second.
Заметьте, что так как порядок обхода виджета second изменился, то вы должны упорядочить церь следующим образом:
setTabOrder(a, b); // a на b setTabOrder(b, c); // a на b на c setTabOrder(c, d); // a на b на c на d
Но не так:
// НЕПРАВИЛЬНО setTabOrder(c, d); // c на d setTabOrder(a, b); // a на b И c на d setTabOrder(b, c); // a на b на c, но не c на d
If first or second has a focus proxy, setTabOrder() correctly substitutes the proxy.
See also setFocusPolicy(), setFocusProxy(), and Keyboard Focus.
Sets the window's role to role. This only makes sense for windows on X11.
See also windowRole().
Sets the window state to windowState. The window state is a OR'ed combination of Qt::WindowState: Qt::WindowMinimized, Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
If the window is not visible (i.e. isVisible() returns false), the window state will take effect when show() is called. For visible windows, the change is immediate. For example, to toggle between full-screen and normal mode, use the following code:
w->setWindowState(w->windowState() ^ Qt::WindowFullScreen);
In order to restore and activate a minimized window (while preserving its maximized and/or full-screen state), use the following:
w->setWindowState(w->windowState() & ~Qt::WindowMinimized | Qt::WindowActive);
Calling this function will hide the widget. You must call show() to make the widget visible again.
Note: On some window systems Qt::WindowActive is not immediate, and may be ignored in certain cases.
When the window state changes, the widget receives a changeEvent() of type QEvent::WindowStateChange.
See also Qt::WindowState and windowState().
This function is under development and is subject to change.
Sets the window surface to be the surface specified. The QWidget takes will ownership of the surface. widget itself is deleted.
Эта функция была введена в Qt 4.2.
See also windowSurface().
Shows the widget and its child widgets. This function is equivalent to setVisible(true).
See also raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(), showNormal(), and isVisible().
This event handler can be reimplemented in a subclass to receive widget show events which are passed in the event parameter.
Non-spontaneous show events are sent to widgets immediately before they are shown. The spontaneous show events of windows are delivered afterwards.
Note: A widget receives spontaneous show and hide events when its mapping status is changed by the window system, e.g. a spontaneous hide event when the user minimizes the window, and a spontaneous show event when the window is restored again. After receiving a spontaneous hide event, a widget is still considered visible in the sense of isVisible().
See also visible, event(), and QShowEvent.
Shows the widget in full-screen mode.
Calling this function only affects windows.
To return from full-screen mode, call showNormal().
Full-screen mode works fine under Windows, but has certain problems under X. These problems are due to limitations of the ICCCM protocol that specifies the communication between X11 clients and the window manager. ICCCM simply does not understand the concept of non-decorated full-screen windows. Therefore, the best we can do is to request a borderless window and place and resize it to fill the entire screen. Depending on the window manager, this may or may not work. The borderless window is requested using MOTIF hints, which are at least partially supported by virtually all modern window managers.
An alternative would be to bypass the window manager entirely and create a window with the Qt::X11BypassWindowManagerHint flag. This has other severe problems though, like totally broken keyboard focus and very strange effects on desktop changes or when the user raises other windows.
X11 window managers that follow modern post-ICCCM specifications support full-screen mode properly.
See also showNormal(), showMaximized(), show(), hide(), and isVisible().
Shows the widget maximized.
Calling this function only affects windows.
On X11, this function may not work properly with certain window managers. See Window Geometry for an explanation.
See also setWindowState(), showNormal(), showMinimized(), show(), hide(), and isVisible().
Shows the widget minimized, as an icon.
Calling this function only affects windows.
See also showNormal(), showMaximized(), show(), hide(), isVisible(), and isMinimized().
Restores the widget after it has been maximized or minimized.
Calling this function only affects windows.
See also setWindowState(), showMinimized(), showMaximized(), show(), hide(), and isVisible().
Places the widget under w in the parent widget's stack.
To make this work, the widget itself and w must be siblings.
See also QWidget::setStyle(), QApplication::setStyle(), and QApplication::style().
This event handler, for event event, can be reimplemented in a subclass to receive tablet events for the widget.
If you reimplement this handler, it is very important that you ignore() the event if you do not handle it, so that the widget's parent can interpret it.
Реализация по умолчанию игнорирует это событие.
See also QTabletEvent::ignore(), QTabletEvent::accept(), event(), and QTabletEvent.
Returns true if attribute attribute is set on this widget; otherwise returns false.
Смотрите также setAttribute().
Returns true if the widget is under the mouse cursor; otherwise returns false.
This value is not updated properly during drag and drop operations.
See also enterEvent() and leaveEvent().
Updates the widget unless updates are disabled or the widget is hidden.
This function does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop. This permits Qt to optimize for more speed and less flicker than a call to repaint() does.
Calling update() several times normally results in just one paintEvent() call.
Qt normally erases the widget's area before the paintEvent() call. If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is responsible for painting all its pixels with an opaque color.
See also repaint(), paintEvent(), setUpdatesEnabled(), and Analog Clock Example.
Это перегруженная функция, предоставленная для удобства.
This version updates a rectangle (x, y, w, h) inside the widget.
Это перегруженная функция, предоставленная для удобства.
This version updates a rectangle r inside the widget.
Это перегруженная функция, предоставленная для удобства.
This version repaints a region rgn inside the widget.
Notifies the layout system that this widget has changed and may need to change geometry.
Call this function if the sizeHint() or sizePolicy() have changed.
For explicitly hidden widgets, updateGeometry() is a no-op. The layout system will be notified as soon as the widget is shown.
Updates the widget's micro focus.
Смотрите также QInputContext.
Returns the unobscured region where paint events can occur.
For visible widgets, this is an approximation of the area not covered by other widgets; otherwise, this is an empty region.
The repaint() function calls this function if necessary, so in general you do not need to call it.
This event handler, for event event, can be reimplemented in a subclass to receive wheel events for the widget.
If you reimplement this handler, it is very important that you ignore() the event if you do not handle it, so that the widget's parent can interpret it.
Реализация по умолчанию игнорирует это событие.
See also QWheelEvent::ignore(), QWheelEvent::accept(), event(), and QWheelEvent.
This special event handler can be reimplemented in a subclass to receive native Windows events which are passed in the message parameter.
In your reimplementation of this function, if you want to stop the event being handled by Qt, return true and set result to the value that the window procedure should return. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget.
Warning: This function is not portable.
See also QApplication::winEventFilter().
Returns the window system identifier of the widget.
Portable in principle, but if you use it you are probably about to do something non-portable. Be careful.
Note: We recommend that you do not store this value as it is likely to change during run-time.
See also find().
Returns the window for this widget, i.e. the next ancestor widget that has (or could have) a window-system frame.
If the widget is a window, the widget itself is returned.
Typical usage is changing the window title:
aWidget->window()->setWindowTitle("New Window Title");
See also isWindow().
Returns the window's role, or an empty string.
See also setWindowRole(), windowIcon, and windowTitle.
Returns the current window state. The window state is a OR'ed combination of Qt::WindowState: Qt::WindowMinimized, Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
See also Qt::WindowState and setWindowState().
This function is under development and is subject to change.
Returns the QWindowSurface this widget will be drawn into.
Эта функция была введена в Qt 4.2.
See also setWindowSurface().
Returns the window type of this widget. This is identical to windowFlags() & Qt::WindowType_Mask.
See also windowFlags.
This special event handler can be reimplemented in a subclass to receive native X11 events which are passed in the event parameter.
In your reimplementation of this function, if you want to stop the event being handled by Qt, return true. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget.
Warning: This function is not portable.
See also QApplication::x11EventFilter().
Platform dependent window identifier.
Defines the maximum size for a QWidget object.
The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
See also QWidget::setMaximumSize().
| Copyright © 2008 Nokia | Торговые марки | Qt 4.4.3 |
|
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |