QWidget 类

QWidget 类是所有用户界面对象的基类。 更多...

公共类型

enum RenderFlag { DrawWindowBackground, DrawChildren, IgnoreMask }
flags RenderFlags

特性

公共函数

QWidget (QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags())
virtual ~QWidget ()
bool acceptDrops () const
QString accessibleDescription () const
QString accessibleName () const
QList<QAction *> actions () const
void activateWindow ()
void addAction (QAction * action )
void addActions (QList<QAction *> actions )
void adjustSize ()
bool autoFillBackground () const
QPalette::ColorRole backgroundRole () const
QBackingStore * backingStore () const
QSize baseSize () const
QWidget * childAt (int x , int y ) const
QWidget * childAt (const QPoint & p ) const
QRect childrenRect () const
QRegion childrenRegion () const
void clearFocus ()
void clearMask ()
QMargins contentsMargins () const
QRect contentsRect () const
Qt::ContextMenuPolicy contextMenuPolicy () const
QCursor cursor () const
WId effectiveWinId () const
void ensurePolished () const
Qt::FocusPolicy focusPolicy () const
QWidget * focusProxy () const
QWidget * focusWidget () const
const QFont & font () const
QFontInfo fontInfo () const
QFontMetrics fontMetrics () const
QPalette::ColorRole foregroundRole () const
QRect frameGeometry () const
QSize frameSize () const
const QRect & geometry () const
void getContentsMargins (int * left , int * top , int * right , int * bottom ) const
QPixmap grab (const QRect & rectangle = QRect(QPoint(0, 0), QSize(-1, -1)))
void grabGesture (Qt::GestureType gesture , Qt::GestureFlags flags = Qt::GestureFlags())
void grabKeyboard ()
void grabMouse ()
void grabMouse (const QCursor & cursor )
int grabShortcut (const QKeySequence & key , Qt::ShortcutContext context = Qt::WindowShortcut)
QGraphicsEffect * graphicsEffect () const
QGraphicsProxyWidget * graphicsProxyWidget () const
bool hasEditFocus () const
bool hasFocus () const
virtual bool hasHeightForWidth () const
bool hasMouseTracking () const
bool hasTabletTracking () const
int height () const
virtual int heightForWidth (int w ) const
Qt::InputMethodHints inputMethodHints () const
virtual QVariant inputMethodQuery (Qt::InputMethodQuery query ) const
void insertAction (QAction * before , QAction * action )
void insertActions (QAction * before , QList<QAction *> actions )
bool isActiveWindow () const
bool isAncestorOf (const QWidget * child ) const
bool isEnabled () const
bool isEnabledTo (const QWidget * ancestor ) const
bool isFullScreen () const
bool isHidden () const
bool isMaximized () const
bool isMinimized () const
bool isModal () const
bool isVisible () const
bool isVisibleTo (const QWidget * ancestor ) const
bool isWindow () const
bool isWindowModified () const
QLayout * layout () const
Qt::LayoutDirection layoutDirection () const
QLocale locale () const
QPoint mapFrom (const QWidget * parent , const QPoint & pos ) const
QPoint mapFromGlobal (const QPoint & pos ) const
QPoint mapFromParent (const QPoint & pos ) const
QPoint mapTo (const QWidget * parent , const QPoint & pos ) const
QPoint mapToGlobal (const QPoint & pos ) const
QPoint mapToParent (const QPoint & pos ) const
QRegion mask () const
int maximumHeight () const
QSize maximumSize () const
int maximumWidth () const
int minimumHeight () const
QSize minimumSize () const
virtual QSize minimumSizeHint () const
int minimumWidth () const
void move ( const QPoint & )
void move (int x , int y )
QWidget * nativeParentWidget () const
QWidget * nextInFocusChain () const
QRect normalGeometry () const
void overrideWindowFlags (Qt::WindowFlags flags )
const QPalette & palette () const
QWidget * parentWidget () const
QPoint pos () const
QWidget * previousInFocusChain () const
QRect rect () const
void releaseKeyboard ()
void releaseMouse ()
void releaseShortcut (int id )
void removeAction (QAction * action )
void render (QPaintDevice * target , const QPoint & targetOffset = QPoint(), const QRegion & sourceRegion = QRegion(), QWidget::RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren))
void render (QPainter * painter , const QPoint & targetOffset = QPoint(), const QRegion & sourceRegion = QRegion(), QWidget::RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren))
void repaint (int x , int y , int w , int h )
void repaint (const QRect & rect )
void repaint (const QRegion & rgn )
void resize ( const QSize & )
void resize (int w , int h )
bool restoreGeometry (const QByteArray & geometry )
QByteArray saveGeometry () const
void scroll (int dx , int dy )
void scroll (int dx , int dy , const QRect & r )
void setAcceptDrops (bool on )
void setAccessibleDescription (const QString & description )
void setAccessibleName (const QString & name )
void setAttribute (Qt::WidgetAttribute attribute , bool on = true)
void setAutoFillBackground (bool enabled )
void setBackgroundRole (QPalette::ColorRole role )
void setBaseSize ( const QSize & )
void setBaseSize (int basew , int baseh )
void setContentsMargins (int left , int top , int right , int bottom )
void setContentsMargins (const QMargins & margins )
void setContextMenuPolicy (Qt::ContextMenuPolicy policy )
void setCursor ( const QCursor & )
void setEditFocus (bool enable )
void setFixedHeight (int h )
void setFixedSize (const QSize & s )
void setFixedSize (int w , int h )
void setFixedWidth (int w )
void setFocus (Qt::FocusReason reason )
void setFocusPolicy (Qt::FocusPolicy policy )
void setFocusProxy (QWidget * w )
void setFont ( const QFont & )
void setForegroundRole (QPalette::ColorRole role )
void setGeometry ( const QRect & )
void setGeometry (int x , int y , int w , int h )
void setGraphicsEffect (QGraphicsEffect * effect )
void setInputMethodHints (Qt::InputMethodHints hints )
void setLayout (QLayout * layout )
void setLayoutDirection (Qt::LayoutDirection direction )
void setLocale (const QLocale & locale )
void setMask (const QBitmap & bitmap )
void setMask (const QRegion & region )
void setMaximumHeight (int maxh )
void setMaximumSize ( const QSize & )
void setMaximumSize (int maxw , int maxh )
void setMaximumWidth (int maxw )
void setMinimumHeight (int minh )
void setMinimumSize ( const QSize & )
void setMinimumSize (int minw , int minh )
void setMinimumWidth (int minw )
void setMouseTracking (bool enable )
void setPalette ( const QPalette & )
void setParent (QWidget * parent )
void setParent (QWidget * parent , Qt::WindowFlags f )
void setShortcutAutoRepeat (int id , bool enable = true)
void setShortcutEnabled (int id , bool enable = true)
void setSizeIncrement ( const QSize & )
void setSizeIncrement (int w , int h )
void setSizePolicy ( QSizePolicy )
void setSizePolicy (QSizePolicy::Policy horizontal , QSizePolicy::Policy vertical )
void setStatusTip ( const QString & )
void setStyle (QStyle * style )
void setTabletTracking (bool enable )
void setToolTip ( const QString & )
void setToolTipDuration (int msec )
void setUpdatesEnabled (bool enable )
void setWhatsThis ( const QString & )
void setWindowFilePath (const QString & filePath )
void setWindowFlag (Qt::WindowType flag , bool on = true)
void setWindowFlags (Qt::WindowFlags type )
void setWindowIcon (const QIcon & icon )
void setWindowModality (Qt::WindowModality windowModality )
void setWindowOpacity (qreal level )
void setWindowRole (const QString & role )
void setWindowState (Qt::WindowStates windowState )
void setupUi (QWidget * widget )
QSize size () const
virtual QSize sizeHint () const
QSize sizeIncrement () const
QSizePolicy sizePolicy () const
void stackUnder (QWidget * w )
QString statusTip () const
QStyle * style () const
QString styleSheet () const
bool testAttribute (Qt::WidgetAttribute attribute ) const
QString toolTip () const
int toolTipDuration () const
bool underMouse () const
void ungrabGesture (Qt::GestureType gesture )
void unsetCursor ()
void unsetLayoutDirection ()
void unsetLocale ()
void update (int x , int y , int w , int h )
void update (const QRect & rect )
void update (const QRegion & rgn )
void updateGeometry ()
bool updatesEnabled () const
QRegion visibleRegion () const
QString whatsThis () const
int width () const
WId winId () const
QWidget * window () const
QString windowFilePath () const
Qt::WindowFlags windowFlags () const
QWindow * windowHandle () const
QIcon windowIcon () const
Qt::WindowModality windowModality () const
qreal windowOpacity () const
QString windowRole () const
Qt::WindowStates windowState () const
QString windowTitle () const
Qt::WindowType windowType () const
int x () const
int y () const

重实现公共函数

virtual QPaintEngine * paintEngine () const override

公共槽

bool close ()
void hide ()
void lower ()
void raise ()
void repaint ()
void setDisabled (bool disable )
void setEnabled ( bool )
void setFocus ()
void setHidden (bool hidden )
void setStyleSheet (const QString & styleSheet )
virtual void setVisible (bool visible )
void setWindowModified ( bool )
void setWindowTitle ( const QString & )
void show ()
void showFullScreen ()
void showMaximized ()
void showMinimized ()
void showNormal ()
void update ()

信号

void customContextMenuRequested (const QPoint & pos )
void windowIconChanged (const QIcon & icon )
void windowTitleChanged (const QString & title )

静态公共成员

QWidget * createWindowContainer (QWindow * window , QWidget * parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags())
QWidget * find (WId id )
QWidget * keyboardGrabber ()
QWidget * mouseGrabber ()
void setTabOrder (QWidget * first , QWidget * second )
const QMetaObject staticMetaObject

保护函数

virtual void actionEvent (QActionEvent * event )
virtual void changeEvent (QEvent * event )
virtual void closeEvent (QCloseEvent * event )
virtual void contextMenuEvent (QContextMenuEvent * event )
void create (WId window = 0, bool initializeWindow = true, bool destroyOldWindow = true)
void destroy (bool destroyWindow = true, bool destroySubWindows = true)
virtual void dragEnterEvent (QDragEnterEvent * event )
virtual void dragLeaveEvent (QDragLeaveEvent * event )
virtual void dragMoveEvent (QDragMoveEvent * event )
virtual void dropEvent (QDropEvent * event )
virtual void enterEvent (QEvent * event )
virtual void focusInEvent (QFocusEvent * event )
bool focusNextChild ()
virtual bool focusNextPrevChild (bool next )
virtual void focusOutEvent (QFocusEvent * event )
bool focusPreviousChild ()
virtual void hideEvent (QHideEvent * event )
virtual void inputMethodEvent (QInputMethodEvent * event )
virtual void keyPressEvent (QKeyEvent * event )
virtual void keyReleaseEvent (QKeyEvent * event )
virtual void leaveEvent (QEvent * event )
virtual void mouseDoubleClickEvent (QMouseEvent * event )
virtual void mouseMoveEvent (QMouseEvent * event )
virtual void mousePressEvent (QMouseEvent * event )
virtual void mouseReleaseEvent (QMouseEvent * event )
virtual void moveEvent (QMoveEvent * event )
virtual bool nativeEvent (const QByteArray & eventType , void * message , long * result )
virtual void paintEvent (QPaintEvent * event )
virtual void resizeEvent (QResizeEvent * event )
virtual void showEvent (QShowEvent * event )
virtual void tabletEvent (QTabletEvent * event )
virtual void wheelEvent (QWheelEvent * event )

重实现保护函数

virtual bool event (QEvent * event ) override
virtual void initPainter (QPainter * painter ) const override
virtual int metric (QPaintDevice::PaintDeviceMetric m ) const override

保护槽

详细描述

QWidget 类是所有用户界面对象的基类。

The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it.

A widget that is not embedded in a parent widget is called a window. Usually, windows have a frame and a title bar, although it is also possible to create windows without such decoration using suitable window flags ). In Qt, QMainWindow 和各种子类化 QDialog 是最常见的窗口类型。

Every widget's constructor accepts one or two standard arguments:

  1. QWidget *parent = 0 is the parent of the new widget. If it is 0 (the default), the new widget will be a window. If not, it will be a child of parent , and be constrained by parent 's geometry (unless you specify Qt::Window as window flag).
  2. Qt::WindowFlags f = 0 (where available) sets the window flags; the default is suitable for almost all widgets, but to get, for example, a window without a window system frame, you must use special flags.

QWidget has many member functions, but some of them have little direct functionality; for example, QWidget has a font property, but never uses this itself. There are many subclasses which provide real functionality, such as QLabel , QPushButton , QListWidget ,和 QTabWidget .

顶层和子级 Widget

A widget without a parent widget is always an independent window (top-level widget). For these widgets, setWindowTitle () 和 setWindowIcon () set the title bar and icon respectively.

Non-window widgets are child widgets, displayed within their parent widgets. Most widgets in Qt are mainly useful as child widgets. 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 .

A parent widget containing various child widgets.

The diagram above shows a QGroupBox widget being used to hold various child widgets in a layout provided by QGridLayout QLabel child widgets have been outlined to indicate their full sizes.

若希望使用 QWidget to hold child widgets you will usually want to add a layout to the parent QWidget 。见 布局管理 了解更多信息。

复合 Widget

当 Widget 被用作分组多个子级 Widget 的容器时,它被称为复合 Widget。这些可以被创建,通过构造 Widget 采用所需视觉特性 QFrame ,例如:把子级 Widget 添加给它,通常由布局进行管理。上图展示使用 Qt Designer 创建这种。

Composite widgets can also be created by subclassing a standard widget, such as QWidget or QFrame ,并在子类的构造函数中添加必要布局和子级 Widget。许多 随 Qt 提供的范例 使用这种途径,且它还涵盖于 Qt 教程 .

自定义 Widget 和描绘

Since QWidget 是子类化的 QPaintDevice ,子类可以被用于显示由一系列描绘操作组成的自定义内容,采用实例化的 QPainter 类。此途径对比画布样式途径使用 图形视图框架 ,其中的项由应用程序添加到场景,并由框架本身渲染。

每个 Widget 履行所有描绘操作,都在其 paintEvent () 函数。这被调用,每当 Widget 需要被重新绘制时,作为某些外部改变的结果或当应用程序请求时。

指针式时钟范例 展示简单 Widget 如何处理描绘事件。

大小提示和大小策略

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 ().

By default, composite widgets which do not provide a size hint will be sized according to the space requirements of their child widgets.

The size policy lets you supply good default behavior for the layout management system, so that other widgets can contain and manage yours easily. The default size policy indicates that the size hint represents the preferred size of the widget, and this is often good enough for many widgets.

注意: The size of top-level widgets are constrained to 2/3 of the desktop's height and width. You can resize () the widget manually if these bounds are inadequate.

事件

Widgets respond to events that are typically caused by user actions. Qt delivers events to widgets by calling specific event handler functions with instances of QEvent subclasses containing information about each event.

If your widget only contains child widgets, you probably do not need to implement any event handlers. If you want to detect a mouse click in a child widget call the child's underMouse () function inside the widget's mousePressEvent ().

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 here is a brief overview of the events that are relevant to QWidget , starting with the most common ones:

  • paintEvent () is called whenever the widget needs to be repainted. Every widget displaying custom content must implement it. Painting using a QPainter can only take place in a paintEvent () or a function called by a paintEvent ().
  • resizeEvent () is called when the widget has been resized.
  • mousePressEvent () is called when a mouse button is pressed while the mouse cursor is inside the widget, or when the widget has grabbed the mouse using grabMouse (). Pressing the mouse without releasing it is effectively the same as calling grabMouse ().
  • mouseReleaseEvent () is called when a mouse button is released. A widget receives mouse release events when it has received the corresponding mouse press event. This means that if the user presses the mouse inside your widget, then drags the mouse somewhere else before releasing the mouse button, your widget receives the release event. There is one exception: if a popup menu appears while the mouse button is held down, this popup immediately steals the mouse events.
  • mouseDoubleClickEvent () is called when the user double-clicks in the widget. If the user double-clicks, the widget receives a mouse press event, a mouse release event, (a mouse click event,) a second mouse press, this event and finally a second mouse release event. (Some mouse move events may also be received if the mouse is not held steady during this operation.) It is not possible to distinguish a click from a double-click until the second click arrives. (This is one reason why most GUI books recommend that double-clicks be an extension of single-clicks, rather than trigger a different action.)

Widgets that accept keyboard input need to reimplement a few more event handlers:

  • keyPressEvent () is called whenever a key is pressed, and again when a key has been held down long enough for it to auto-repeat. The Tab and Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement QWidget::event ().
  • focusInEvent () is called when the widget gains keyboard focus (assuming you have called setFocusPolicy ()). Well-behaved widgets indicate that they own the keyboard focus in a clear but discreet way.
  • focusOutEvent () is called when the widget loses keyboard focus.

You may be required to also reimplement some of the less common event handlers:

  • mouseMoveEvent () is called whenever the mouse moves while a mouse button is held down. This can be useful during drag and drop operations. If you call setMouseTracking (true), you get mouse move events even when no buttons are held down. (See also the 拖放 指南。)
  • keyReleaseEvent () is called whenever a key is released and while it is held down (if the key is auto-repeating). In that case, the widget will receive a pair of key release and key press event for every repeat. The Tab and Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement QWidget::event ().
  • wheelEvent () is called whenever the user turns the mouse wheel while the widget has the focus.
  • enterEvent () is called when the mouse enters the widget's screen space. (This excludes screen space owned by any of the widget's children.)
  • leaveEvent () is called when the mouse leaves the widget's screen space. If the mouse enters a child widget it will not cause a leaveEvent ().
  • moveEvent () is called when the widget has been moved relative to its parent.
  • closeEvent () is called when the user closes the widget (or when close () 被调用)。

There are also some rather obscure events described in the documentation for QEvent::Type . To handle these events, you need to reimplement event () directly.

The default implementation of event () handles Tab and Shift+Tab (to move the keyboard focus), and passes on most of the other events to one of the more specialized handlers above.

Events and the mechanism used to deliver them are covered in 事件系统 .

函数和特性组

Context 函数和特性
窗口函数 show (), hide (), raise (), lower (), close ().
顶层窗口 windowModified , windowTitle , windowIcon , isActiveWindow , activateWindow (), minimized , showMinimized (), maximized , showMaximized (), fullScreen , showFullScreen (), showNormal ().
窗口上下文 update (), repaint (), scroll ().
Geometry pos , x (), y (), rect , size , width (), height (), move (), resize (), sizePolicy , sizeHint (), minimumSizeHint (), updateGeometry (), layout (), frameGeometry , geometry , childrenRect , childrenRegion , adjustSize (), mapFromGlobal (), mapToGlobal (), mapFromParent (), mapToParent (), maximumSize , minimumSize , sizeIncrement , baseSize , setFixedSize ()
Mode visible , isVisibleTo (), enabled , isEnabledTo (), modal , isWindow (), mouseTracking , updatesEnabled , visibleRegion ().
外观和感觉 style (), setStyle (), styleSheet , cursor , font , palette , backgroundRole (), setBackgroundRole (), fontInfo (), fontMetrics ().
键盘聚焦函数 focus , focusPolicy , setFocus (), clearFocus (), setTabOrder (), setFocusProxy (), focusNextChild (), focusPreviousChild ().
鼠标和键盘抓取 grabMouse (), releaseMouse (), grabKeyboard (), releaseKeyboard (), mouseGrabber (), keyboardGrabber ().
事件处理程序 event (), mousePressEvent (), mouseReleaseEvent (), mouseDoubleClickEvent (), mouseMoveEvent (), keyPressEvent (), keyReleaseEvent (), focusInEvent (), focusOutEvent (), wheelEvent (), enterEvent (), leaveEvent (), paintEvent (), moveEvent (), resizeEvent (), closeEvent (), dragEnterEvent (), dragMoveEvent (), dragLeaveEvent (), dropEvent (), childEvent (), showEvent (), hideEvent (), customEvent (). changeEvent (),
系统函数 parentWidget (), window (), setParent (), winId (), find (), metric ().
上下文菜单 contextMenuPolicy , contextMenuEvent (), customContextMenuRequested (), actions ()
交互式帮助 setToolTip (), setWhatsThis ()

Widget 样式表

In addition to the standard widget styles for each platform, widgets can also be styled according to rules specified in a style sheet . This feature enables you to customize the appearance of specific widgets to provide visual cues to users about their purpose. For example, a button could be styled in a particular way to indicate that it performs a destructive action.

The use of widget style sheets is described in more detail in the Qt 样式表 文档。

透明度和双缓冲

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

Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been deprecated. Instead, the contents of parent widgets are propagated by default to each of their children as long as Qt::WA_PaintOnScreen is not set. Custom widgets can be written to take advantage of this feature by updating irregular regions (to create non-rectangular child widgets), or painting with colors that have less than full alpha component. The following diagram shows how attributes and properties of a custom widget can be fine-tuned to achieve different effects.

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:

  • The left widget has no additional properties or widget attributes set. This default state suits most custom widgets using transparency, are irregularly-shaped, or do not paint over their entire area with an opaque brush.
  • The center widget has the autoFillBackground property set. This property is used with custom widgets that rely on the widget to supply a default background, and do not paint over their entire area with an opaque brush.
  • The right widget has the Qt::WA_OpaquePaintEvent widget attribute set. This indicates that the widget will paint over its entire area with opaque colors. The widget's area will initially be uninitialized , represented in the diagram with a red diagonal grid pattern that shines through the overpainted area. The Qt::WA_OpaquePaintArea attribute is useful for widgets that need to paint their own specialized contents quickly and do not need a default filled background.

To rapidly update 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 ().

To rapidly update custom widgets that constantly paint over their entire areas with opaque content, e.g., 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. Depending on your requirements, you should choose either one of them.

Since Qt 4.1, the contents of parent widgets are also propagated to standard Qt widgets. This can lead to some unexpected results if the parent widget is decorated in a non-standard way, as shown in the diagram below.

The scope for customizing the painting behavior of standard Qt widgets, without resorting to subclassing, is slightly less than that possible for custom widgets. Usually, the desired appearance of a standard widget can be achieved by setting its autoFillBackground 特性。

创建半透明窗口

Since Qt 4.5, it has been possible to create windows with translucent regions on window systems that support compositing.

To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground 属性采用 setAttribute () and ensure that its background is painted with non-opaque colors in the regions you want to be partially transparent.

平台注意事项:

  • X11: This feature relies on the use of an X server that supports ARGB visuals and a compositing window manager.
  • Windows: The widget needs to have the Qt::FramelessWindowHint window flag set for the translucency to work.

本地 Widget vs 外来 Widget

Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing system. They do not have a native window handle associated with them. This feature significantly speeds up widget painting, resizing, and removes flicker.

Should you require the old behavior with native windows, you can choose one of the following options:

  1. 使用 QT_USE_NATIVE_WINDOWS=1 在环境中。
  2. 设置 Qt::AA_NativeWindows attribute on your application. All widgets will be native widgets.
  3. 设置 Qt::WA_NativeWindow attribute on widgets: The widget itself and all of its ancestors will become native (unless Qt::WA_DontCreateNativeAncestors is set).
  4. 调用 QWidget::winId to enforce a native window (this implies 3).
  5. 设置 Qt::WA_PaintOnScreen attribute to enforce a native window (this implies 3).

另请参阅 QEvent , QPainter , QGridLayout ,和 QBoxLayout .

成员类型文档编制

enum QWidget:: RenderFlag
flags QWidget:: RenderFlags

此枚举描述如何渲染 Widget 当调用 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. By default, this option is enabled.
QWidget::DrawChildren 0x2 If you enable this option, the widget's children are rendered recursively into the target. By default, this option is enabled.
QWidget::IgnoreMask 0x4 若启用此选项,Widget 的 QWidget::mask () is ignored when rendering into the target. By default, this option is disabled.

This enum was introduced or modified in Qt 4.3.

RenderFlags 类型是 typedef 对于 QFlags <RenderFlag>. It stores an OR combination of RenderFlag values.

特性文档编制

acceptDrops : bool

此特性保持是否为此 Widget 启用下落事件

把此特性设为 true 向系统宣布此 Widget may 能够接受下落事件。

若 Widget 是桌面 ( windowType () == Qt::Desktop ),这可能失败,若另一应用程序正在使用桌面;可以调用 acceptDrops() 去测试,若这发生。

警告: 不要在拖放事件处理程序中修改此特性。

默认情况下,此特性为 false .

访问函数:

bool acceptDrops () const
void setAcceptDrops (bool on )

另请参阅 拖放 .

accessibleDescription : QString

This property holds the widget's description as seen by assistive technologies

The accessible description of a widget should convey what a widget does. While the accessibleName should be a short and consise string (e.g. Save ), the description should give more context, such as Saves the current document .

This property has to be localized .

By default, this property contains an empty string and Qt falls back to using the tool tip to provide this information.

访问函数:

QString accessibleDescription () const
void setAccessibleDescription (const QString & description )

另请参阅 QWidget::accessibleName and QAccessibleInterface::text ().

accessibleName : QString

This property holds the widget's name as seen by assistive technologies

This is the primary name by which assistive technology such as screen readers announce this widget. For most widgets setting this property is not required. For example for QPushButton the button's text will be used.

It is important to set this property when the widget does not provide any text. For example a button that only contains an icon needs to set this property to work with screen readers. The name should be short and equivalent to the visual information conveyed by the widget.

This property has to be localized .

默认情况下,此特性包含空字符串。

访问函数:

QString accessibleName () const
void setAccessibleName (const QString & name )

另请参阅 QWidget::accessibleDescription and QAccessibleInterface::text ().

autoFillBackground : bool

This property holds whether the widget background is filled automatically

If enabled, this property 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 .

In addition, Windows are always filled with QPalette::Window , unless the WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.

This property cannot be turned off (i.e., set to false) if a widget's parent has a static gradient for its background.

警告: Use this property with caution in conjunction with Qt 样式表 . When a widget has a style sheet with a valid background or a border-image, this property is automatically disabled.

默认情况下,此特性为 false .

This property was introduced in Qt 4.1.

访问函数:

bool autoFillBackground () const
void setAutoFillBackground (bool enabled )

另请参阅 Qt::WA_OpaquePaintEvent , Qt::WA_NoSystemBackground ,和 透明度和双缓冲 .

baseSize : QSize

This property holds the base size of the widget

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.

访问函数:

QSize baseSize () const
void setBaseSize ( const QSize & )
void setBaseSize (int basew , int baseh )

另请参阅 setSizeIncrement ().

childrenRect : const QRect

This property holds the bounding rectangle of the widget's children

Hidden children are excluded.

By default, for a widget with no children, this property contains a rectangle with zero width and height located at the origin.

访问函数:

QRect childrenRect () const

另请参阅 childrenRegion () 和 geometry ().

childrenRegion : const QRegion

This property holds the combined region occupied by the widget's children

Hidden children are excluded.

By default, for a widget with no children, this property contains an empty region.

访问函数:

QRegion childrenRegion () const

另请参阅 childrenRect (), geometry (),和 mask ().

contextMenuPolicy : Qt::ContextMenuPolicy

Widget 如何展示上下文菜单

此特性的默认值为 Qt::DefaultContextMenu ,这意味着 contextMenuEvent () 处理程序被调用。其它值 Qt::NoContextMenu , Qt::PreventContextMenu , Qt::ActionsContextMenu ,和 Qt::CustomContextMenu . With Qt::CustomContextMenu ,信号 customContextMenuRequested () 被发射。

访问函数:

Qt::ContextMenuPolicy contextMenuPolicy () const
void setContextMenuPolicy (Qt::ContextMenuPolicy policy )

另请参阅 contextMenuEvent (), customContextMenuRequested (),和 actions ().

cursor : QCursor

This property holds the cursor shape for this widget

The mouse cursor will assume this shape when it's over this widget. See the list of predefined cursor objects for a range of useful shapes.

An editor widget might use an I-beam cursor:

setCursor(Qt::IBeamCursor);
							

If no cursor has been set, or after a call to unsetCursor(), the parent's cursor is used.

By default, this property contains a cursor with the Qt::ArrowCursor shape.

Some underlying window implementations will reset the cursor if it leaves a widget even if the mouse is grabbed. If you want to have a cursor set for all widgets, even when outside the window, consider QApplication::setOverrideCursor ().

访问函数:

QCursor cursor () const
void setCursor ( const QCursor & )
void unsetCursor ()

另请参阅 QApplication::setOverrideCursor ().

enabled : bool

This property holds whether the widget is enabled

In general an enabled widget handles keyboard and mouse events; a disabled widget does not. An exception is made with QAbstractButton .

Some widgets display themselves differently when they are disabled. For example a button might draw its label grayed out. If your widget needs to know when it becomes enabled or disabled, you can use the changeEvent () with type QEvent::EnabledChange .

Disabling a widget implicitly disables all its children. Enabling respectively enables all child widgets unless they have been explicitly disabled. It it not possible to explicitly enable a child widget which is not a window while its parent widget remains disabled.

默认情况下,此特性为 true .

访问函数:

bool isEnabled () const
void setEnabled ( bool )

另请参阅 isEnabledTo (), QKeyEvent , QMouseEvent ,和 changeEvent ().

focus : const bool

This property holds whether this widget (or its focus proxy) has the keyboard input focus

默认情况下,此特性为 false .

注意: Obtaining the value of this property for a widget is effectively equivalent to checking whether QApplication::focusWidget () refers to the widget.

访问函数:

bool hasFocus () const

另请参阅 setFocus (), clearFocus (), setFocusPolicy (),和 QApplication::focusWidget ().

focusPolicy : Qt::FocusPolicy

此特性保持 Widget 接受键盘聚焦的方式

策略为 Qt::TabFocus 若 Widget 通过 Tab 键接受键盘聚焦, Qt::ClickFocus 若 Widget 通过点击接受聚焦, Qt::StrongFocus 若它接受两者,而 Qt::NoFocus (默认) 若它根本不接受聚焦。

必须为 Widget 启用键盘聚焦,若它处理键盘事件。通常这是由 Widget 的构造函数完成的。例如, QLineEdit 构造函数调用 setFocusPolicy( Qt::StrongFocus ).

若 Widget 有聚焦代理,聚焦策略就会传播给它。

访问函数:

Qt::FocusPolicy focusPolicy () const
void setFocusPolicy (Qt::FocusPolicy policy )

另请参阅 focusInEvent (), focusOutEvent (), keyPressEvent (), keyReleaseEvent (),和 enabled .

font : QFont

此特性保持 Widget 目前设置的字体

This property describes the widget's requested font. The font is used by the widget's style when rendering standard components, and is available as a means to ensure that custom widgets can maintain consistency with the native platform's look and feel. It's common that different platforms, or different styles, define different fonts for an application.

When you assign a new font to a widget, the properties from this font are combined with the widget's default font to form the widget's final font. You can call fontInfo () to get a copy of the widget's final font. The final font is also used to initialize QPainter 's font.

默认取决于系统环境。 QApplication maintains a system/theme font which serves as a default for all widgets. There may also be special font defaults for certain types of widgets. You can also define default fonts for widgets yourself by passing a custom font and the name of a widget to QApplication::setFont (). Finally, the font is matched against Qt's font database to find the best match.

QWidget propagates explicit font properties from parent to child. If you change a specific property on a font and assign that font to a widget, that property will propagate to all the widget's children, overriding any system defaults for that property. Note that fonts by default don't propagate to windows (see isWindow ()) unless the Qt::WA_WindowPropagation attribute is enabled.

QWidget 's font propagation is similar to its palette propagation.

The current style, which is used to render the content of all standard Qt widgets, is free to choose to use the widget font, or in some cases, to ignore it (partially, or completely). In particular, certain styles like GTK style, Mac style, and Windows Vista style, apply special modifications to the widget font to match the platform's native look and feel. Because of this, assigning properties to a widget's font is not guaranteed to change the appearance of the widget. Instead, you may choose to apply a styleSheet .

注意: Qt 样式表 are used on the same widget as setFont(), style sheets will take precedence if the settings conflict.

访问函数:

const QFont & font () const
void setFont ( const QFont & )

另请参阅 fontInfo () 和 fontMetrics ().

frameGeometry : const QRect

geometry of the widget relative to its parent including any window frame

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

By default, this property contains a value that depends on the user's platform and screen geometry.

访问函数:

QRect frameGeometry () const

另请参阅 geometry (), x (), y (),和 pos ().

frameSize : const QSize

This property holds the size of the widget including any window frame

By default, this property contains a value that depends on the user's platform and screen geometry.

访问函数:

QSize frameSize () const

fullScreen : const bool

此特性保持 Widget 是否以全屏模式展示

A widget in full screen mode occupies the whole screen area and does not display window decorations, such as a title bar.

默认情况下,此特性为 false .

访问函数:

bool isFullScreen () const

另请参阅 windowState (), minimized ,和 maximized .

geometry : QRect

此特性保持 Widget 相对于其父级的几何体,但不包括窗口框架

When changing the geometry, the widget, if visible, receives a move event ( moveEvent ()) and/or a resize event ( resizeEvent ()) immediately. If the widget is not currently visible, it is guaranteed to receive appropriate events before it is shown.

The size component is adjusted if it lies outside the range defined by minimumSize () 和 maximumSize ().

警告: Calling setGeometry() inside resizeEvent () 或 moveEvent () can lead to infinite recursion.

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

By default, this property contains a value that depends on the user's platform and screen geometry.

访问函数:

const QRect & geometry () const
void setGeometry (int x , int y , int w , int h )
void setGeometry ( const QRect & )

另请参阅 frameGeometry (), rect (), move (), resize (), moveEvent (), resizeEvent (), minimumSize (),和 maximumSize ().

height : const int

This property holds the height of the widget excluding any window frame

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

注意: Do not use this function to find the height of a screen on a multiple screen desktop . Read this note 了解细节。

By default, this property contains a value that depends on the user's platform and screen geometry.

访问函数:

int height () const

另请参阅 geometry , width ,和 size .

inputMethodHints : Qt::InputMethodHints

What input method specific hints the widget has.

This is only relevant for input widgets. It is used by the input method to retrieve hints as to how the input method should operate. For example, if the Qt::ImhFormattedNumbersOnly flag is set, the input method may change its visual components to reflect that only numbers can be entered.

警告: Some widgets require certain flags in order to work as intended. To set a flag, do w->setInputMethodHints(w->inputMethodHints()|f) instead of w->setInputMethodHints(f) .

注意: The flags are only hints, so the particular input method implementation is free to ignore them. If you want to be sure that a certain type of characters are entered, you should also set a QValidator on the widget.

默认值为 Qt::ImhNone .

This property was introduced in Qt 4.6.

访问函数:

Qt::InputMethodHints inputMethodHints () const
void setInputMethodHints (Qt::InputMethodHints hints )

另请参阅 inputMethodQuery ().

isActiveWindow : const bool

此特性保持此 Widget 的窗口,是否为活动窗口

活动窗口是包含拥有键盘聚焦的 Widget 的窗口 (窗口可能仍然拥有聚焦,若它没有 Widget 或其 Widget 不接受键盘聚焦)。

当弹出窗口可见时,此特性为 true for both the active window and for the popup.

默认情况下,此特性为 false .

访问函数:

bool isActiveWindow () const

另请参阅 activateWindow () 和 QApplication::activeWindow ().

layoutDirection : Qt::LayoutDirection

此特性保持用于该 Widget 的布局方向

默认情况下,此特性被设为 Qt::LeftToRight .

When the layout direction is set on a widget, it will propagate to the widget's children, but not to a child that is a window and not to a child for which setLayoutDirection() has been explicitly called. Also, child widgets added after setLayoutDirection() has been called for the parent do not inherit the parent's layout direction.

This method no longer affects text layout direction since Qt 4.7.

访问函数:

Qt::LayoutDirection layoutDirection () const
void setLayoutDirection (Qt::LayoutDirection direction )
void unsetLayoutDirection ()

另请参阅 QApplication::layoutDirection .

locale : QLocale

This property holds the widget's locale

As long as no special locale has been set, this is either the parent's locale or (if this widget is a top level widget), the default locale.

If the widget displays dates or numbers, these should be formatted using the widget's locale.

This property was introduced in Qt 4.3.

访问函数:

QLocale locale () const
void setLocale (const QLocale & locale )
void unsetLocale ()

另请参阅 QLocale and QLocale::setDefault ().

maximized : const bool

This property holds whether this widget is maximized

This property is only relevant for windows.

注意: 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). This is expected to improve as window manager protocols evolve.

默认情况下,此特性为 false .

访问函数:

bool isMaximized () const

另请参阅 windowState (), showMaximized (), visible , show (), hide (), showNormal (),和 minimized .

maximumHeight : int

This property holds the widget's maximum height in pixels

This property corresponds to the height held by the maximumSize 特性。

By default, this property contains a value of 16777215.

注意: The definition of the QWIDGETSIZE_MAX macro limits the maximum size of widgets.

访问函数:

int maximumHeight () const
void setMaximumHeight (int maxh )

另请参阅 maximumSize and maximumWidth .

maximumSize : QSize

This property holds the widget's maximum size in pixels

The widget cannot be resized to a larger size than the maximum widget size.

By default, this property contains a size in which both width and height have values of 16777215.

注意: The definition of the QWIDGETSIZE_MAX macro limits the maximum size of widgets.

访问函数:

QSize maximumSize () const
void setMaximumSize ( const QSize & )
void setMaximumSize (int maxw , int maxh )

另请参阅 maximumWidth , maximumHeight , minimumSize ,和 sizeIncrement .

maximumWidth : int

This property holds the widget's maximum width in pixels

此特性对应的宽度保持通过 maximumSize 特性。

By default, this property contains a value of 16777215.

注意: The definition of the QWIDGETSIZE_MAX macro limits the maximum size of widgets.

访问函数:

int maximumWidth () const
void setMaximumWidth (int maxw )

另请参阅 maximumSize and maximumHeight .

minimized : const bool

This property holds whether this widget is minimized (iconified)

This property is only relevant for windows.

默认情况下,此特性为 false .

访问函数:

bool isMinimized () const

另请参阅 showMinimized (), visible , show (), hide (), showNormal (),和 maximized .

minimumHeight : int

This property holds the widget's minimum height in pixels

This property corresponds to the height held by the minimumSize 特性。

默认情况下,此特性拥有 0 值。

访问函数:

int minimumHeight () const
void setMinimumHeight (int minh )

另请参阅 minimumSize and minimumWidth .

minimumSize : QSize

This property holds the widget's minimum size

The widget cannot be resized to a smaller size than the minimum widget size. The widget's size is forced to the minimum size if the current size is smaller.

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) .

By default, this property contains a size with zero width and height.

访问函数:

QSize minimumSize () const
void setMinimumSize ( const QSize & )
void setMinimumSize (int minw , int minh )

另请参阅 minimumWidth , minimumHeight , maximumSize ,和 sizeIncrement .

minimumSizeHint : const QSize

This property holds the recommended minimum size for the widget

If the value of this property is an invalid size, no minimum size is recommended.

The default implementation of minimumSizeHint() returns an invalid size if there is no layout for this widget, and returns the layout's minimum size otherwise. Most built-in widgets reimplement 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.

访问函数:

virtual QSize minimumSizeHint () const

另请参阅 QSize::isValid (), resize (), setMinimumSize (),和 sizePolicy ().

minimumWidth : int

此特性保持 Widget 的最小宽度 (以像素为单位)

此特性对应的宽度保持通过 minimumSize 特性。

默认情况下,此特性拥有 0 值。

访问函数:

int minimumWidth () const
void setMinimumWidth (int minw )

另请参阅 minimumSize and minimumHeight .

此特性保持 Widget 是否为模态小部件

This property only makes sense for windows. A modal widget prevents widgets in all other windows from getting any input.

默认情况下,此特性为 false .

访问函数:

bool isModal () const

另请参阅 isWindow (), windowModality ,和 QDialog .

mouseTracking : bool

此特性保持是否为 Widget 启用鼠标跟踪

若鼠标跟踪被禁用 (默认),当至少按下一鼠标按钮移动鼠标时,Widget 才接收鼠标移动事件。

若鼠标跟踪被启用,Widget 接收鼠标移动事件,即使没有按钮被按下。

访问函数:

bool hasMouseTracking () const
void setMouseTracking (bool enable )

另请参阅 mouseMoveEvent ().

normalGeometry : const QRect

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.

访问函数:

QRect normalGeometry () const

另请参阅 QWidget::windowState () 和 QWidget::geometry .

palette : QPalette

此特性保持 Widget 的调色板

This property describes the widget's palette. The palette is used by the widget's style when rendering standard components, and is available as a means to ensure that custom widgets can maintain consistency with the native platform's look and feel. It's common that different platforms, or different styles, have different palettes.

When you assign a new palette to a widget, the color roles from this palette are combined with the widget's default palette to form the widget's final palette. The palette entry for the widget's background role is used to fill the widget's background (see QWidget::autoFillBackground ), and the foreground role initializes QPainter 's pen.

默认取决于系统环境。 QApplication maintains a system/theme palette which serves as a default for all widgets. There may also be special palette defaults for certain types of widgets (e.g., on Windows Vista, all classes that derive from QMenuBar have a special default palette). You can also define default palettes for widgets yourself by passing a custom palette and the name of a widget to QApplication::setPalette (). Finally, the style always has the option of polishing the palette as it's assigned (see QStyle::polish ()).

QWidget propagates explicit palette roles from parent to child. If you assign a brush or color to a specific role on a palette and assign that palette to a widget, that role will propagate to all the widget's children, overriding any system defaults for that role. Note that palettes by default don't propagate to windows (see isWindow ()) unless the Qt::WA_WindowPropagation attribute is enabled.

QWidget 's palette propagation is similar to its font propagation.

The current style, which is used to render the content of all standard Qt widgets, is free to choose colors and brushes from the widget palette, or in some cases, to ignore the palette (partially, or completely). In particular, certain styles like GTK style, Mac style, and Windows Vista style, depend on third party APIs to render the content of widgets, and these styles typically do not follow the palette. Because of this, assigning roles to a widget's palette is not guaranteed to change the appearance of the widget. Instead, you may choose to apply a styleSheet .

警告: Do not use this function in conjunction with Qt 样式表 . When using style sheets, the palette of a widget can be customized using the "color", "background-color", "selection-color", "selection-background-color" and "alternate-background-color".

访问函数:

const QPalette & palette () const
void setPalette ( const QPalette & )

另请参阅 QApplication::palette (), QWidget::font (),和 Qt 样式表 .

pos : QPoint

This property holds the position of the widget within its parent widget

If the widget is a window, the position is that of the widget on the desktop, including its frame.

When changing the position, the widget, if visible, receives a move event ( moveEvent ()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown.

By default, this property contains a position that refers to the origin.

警告: Calling move() or setGeometry () inside moveEvent () can lead to infinite recursion.

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

访问函数:

QPoint pos () const
void move (int x , int y )
void move ( const QPoint & )

另请参阅 frameGeometry , size , x (),和 y ().

rect : const QRect

This property holds the internal geometry of the widget excluding any window frame

The rect property equals QRect (0, 0, width (), height ()).

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

By default, this property contains a value that depends on the user's platform and screen geometry.

访问函数:

QRect rect () const

另请参阅 size .

size : QSize

This property holds the size of the widget excluding any window frame

If the widget is visible when it is being resized, it receives a resize event ( resizeEvent ()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown.

The size is adjusted if it lies outside the range defined by minimumSize () 和 maximumSize ().

By default, this property contains a value that depends on the user's platform and screen geometry.

警告: Calling resize() or setGeometry () inside resizeEvent () can lead to infinite recursion.

注意: Setting the size to QSize(0, 0) will cause the widget to not appear on screen. This also applies to windows.

访问函数:

QSize size () const
void resize (int w , int h )
void resize ( const QSize & )

另请参阅 pos , geometry , minimumSize , maximumSize , resizeEvent (),和 adjustSize ().

sizeHint : const QSize

此特性保持 Widget 的推荐尺寸

若此特性的值是无效尺寸,则没有尺寸被推荐。

默认 sizeHint() 实现返回无效尺寸,若此 Widget 没有布局;否则,返回布局的首选尺寸。

访问函数:

virtual QSize sizeHint () const

另请参阅 QSize::isValid (), minimumSizeHint (), sizePolicy (), setMinimumSize (),和 updateGeometry ().

sizeIncrement : QSize

此特性保持 Widget 的大小增量

当用户重置窗口尺寸时,尺寸将按 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();
							

Note that while you can set the size increment for all widgets, it only affects windows.

By default, this property contains a size with zero width and height.

警告: The size increment has no effect under Windows, and may be disregarded by the window manager on X11.

访问函数:

QSize sizeIncrement () const
void setSizeIncrement ( const QSize & )
void setSizeIncrement (int w , int h )

另请参阅 size , minimumSize ,和 maximumSize .

sizePolicy : QSizePolicy

This property holds the default layout behavior of the widget

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. Button-like widgets set the size policy to specify that they may stretch horizontally, but are fixed vertically. 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 ().

访问函数:

QSizePolicy sizePolicy () const
void setSizePolicy ( QSizePolicy )
void setSizePolicy (QSizePolicy::Policy horizontal , QSizePolicy::Policy vertical )

另请参阅 sizeHint (), QLayout , QSizePolicy ,和 updateGeometry ().

statusTip : QString

此特性保持 Widget 的状态提示

默认情况下,此特性包含空字符串。

访问函数:

QString statusTip () const
void setStatusTip ( const QString & )

另请参阅 toolTip and whatsThis .

styleSheet : QString

此特性保持 Widget 的样式表

The style sheet contains a textual description of customizations to the widget's style, as described in the Qt 样式表 文档。

从 Qt 4.5 起,Qt 样式表完全支持 macOS .

警告: Qt style sheets are currently not supported for custom QStyle subclasses. We plan to address this in some future release.

This property was introduced in Qt 4.2.

访问函数:

QString styleSheet () const
void setStyleSheet (const QString & styleSheet )

另请参阅 setStyle (), QApplication::styleSheet ,和 Qt 样式表 .

tabletTracking : bool

This property holds whether tablet tracking is enabled for the widget

If tablet tracking is disabled (the default), the widget only receives tablet move events when the stylus is in contact with the tablet, or at least one stylus button is pressed, while the stylus is being moved.

If tablet tracking is enabled, the widget receives tablet move events even while hovering in proximity. This is useful for monitoring position as well as the auxiliary properties such as rotation and tilt, and providing feedback in the UI.

This property was introduced in Qt 5.9.

访问函数:

bool hasTabletTracking () const
void setTabletTracking (bool enable )

另请参阅 tabletEvent ().

toolTip : QString

This property holds the widget's tooltip

Note that by default tooltips are only shown for widgets that are children of the active window. 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).

默认情况下,此特性包含空字符串。

访问函数:

QString toolTip () const
void setToolTip ( const QString & )

另请参阅 QToolTip , statusTip ,和 whatsThis .

toolTipDuration : int

此特性保持 Widget 的工具提示持续时间

Specifies how long time the tooltip will be displayed, in milliseconds. If the value is -1 (default) the duration is calculated depending on the length of the tooltip.

This property was introduced in Qt 5.2.

访问函数:

int toolTipDuration () const
void setToolTipDuration (int msec )

另请参阅 toolTip .

updatesEnabled : bool

此特性保持是否启用更新

An updates enabled widget receives paint events and has a system background; a disabled widget does not. This also implies that calling update () 和 repaint () 无效,若更新被禁用。

默认情况下,此特性为 true .

setUpdatesEnabled() is normally used to disable updates for a short period of time, for instance to avoid screen flicker during large changes. In Qt, widgets normally do not generate screen flicker, but on X11 the server might erase regions on the screen when widgets get hidden before they can be replaced by other widgets. Disabling updates solves this.

范例:

setUpdatesEnabled(false);
bigVisualChanges();
setUpdatesEnabled(true);
							

Disabling a widget implicitly disables all its children. Enabling a widget enables all child widgets except top-level widgets or those that have been explicitly disabled. Re-enabling updates implicitly calls update () on the widget.

访问函数:

bool updatesEnabled () const
void setUpdatesEnabled (bool enable )

另请参阅 paintEvent ().

visible : bool

此特性保持 Widget 是否可见

调用 setVisible(true) 或 show () sets the widget to visible status if all its parent widgets up to the window are visible. If an ancestor is not visible, the widget won't become visible until all its ancestors are shown. If its size or position has changed, Qt guarantees that a widget gets move and resize events just before it is shown. 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. An explicitly hidden widget will never become visible, even if all its ancestors become visible, unless you show it.

A widget receives show and hide events when its visibility status changes. Between a hide and a show event, there is no need to waste CPU cycles preparing or displaying information to the user. A video application, for example, might simply stop generating new frames.

A widget that happens to be obscured by other windows on the screen is considered to be visible. The same applies to iconified windows and windows that exist on another virtual desktop (on platforms that support this concept). 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.

几乎从不需要重新实现 setVisible() 函数。若需要在 Widget 被展示之前更改某些设置,请使用 showEvent () 代替。若需要做一些延迟初始化,请使用 Polish (抛光) 事件,被交付给 event () 函数。

访问函数:

bool isVisible () const
virtual void setVisible (bool visible )

另请参阅 show (), hide (), isHidden (), isVisibleTo (), isMinimized (), showEvent (),和 hideEvent ().

whatsThis : QString

此特性保持 Widget 的 What's This 帮助文本。

默认情况下,此特性包含空字符串。

访问函数:

QString whatsThis () const
void setWhatsThis ( const QString & )

另请参阅 QWhatsThis , QWidget::toolTip ,和 QWidget::statusTip .

width : const int

This property holds the width of the widget excluding any window frame

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

注意: Do not use this function to find the width of a screen on a multiple screen desktop . Read this note 了解细节。

By default, this property contains a value that depends on the user's platform and screen geometry.

访问函数:

int width () const

另请参阅 geometry , height ,和 size .

windowFilePath : QString

此特性保持与 Widget 关联的文件路径

此特性仅对窗口有意义。它把文件路径与窗口关联。若设置文件路径,但未设置窗口标题,则 Qt 会把窗口标题设为指定路径的文件名,获得使用 QFileInfo::fileName ().

若在任何时候设置了窗口标题,则窗口标题优先,且将被展示而非文件路径字符串。

Additionally, on macOS , this has an added benefit that it sets the 代理图标 为窗口,假定文件路径存在。

此特性包含空字符串,若未设置文件路径。

默认情况下,此特性包含空字符串。

This property was introduced in Qt 4.4.

访问函数:

QString windowFilePath () const
void setWindowFilePath (const QString & filePath )

另请参阅 windowTitle and windowIcon .

windowFlags : Qt::WindowFlags

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.

注意: 此函数调用 setParent () when changing the flags for a window, causing the widget to be hidden. You must call show () to make the widget visible again..

访问函数:

Qt::WindowFlags windowFlags () const
void setWindowFlags (Qt::WindowFlags type )

另请参阅 windowType (), setWindowFlag (),和 窗口标志范例 .

windowIcon : QIcon

This property holds the widget's icon

This property only makes sense for windows. If no icon has been set, windowIcon() returns the application icon ( QApplication::windowIcon ()).

访问函数:

QIcon windowIcon () const
void setWindowIcon (const QIcon & icon )

通知信号:

void windowIconChanged (const QIcon & icon )

另请参阅 windowTitle .

windowModality : Qt::WindowModality

This property holds which windows are blocked by the modal widget

This property only makes sense for windows. A modal widget prevents widgets in other windows from getting input. The value of this property controls which windows are blocked when the widget is visible. Changing this property while the window is visible has no effect; you must hide () the widget first, then show () it again.

默认情况下,此特性为 Qt::NonModal .

This property was introduced in Qt 4.1.

访问函数:

Qt::WindowModality windowModality () const
void setWindowModality (Qt::WindowModality windowModality )

另请参阅 isWindow (), QWidget::modal ,和 QDialog .

windowModified : bool

This property holds whether the document shown in the window has unsaved changes

A modified window is a window whose content has changed but has not been saved to disk. This flag will have different effects varied by the platform. On macOS the close button will have a modified look; on other platforms, the window title will have an '*' (asterisk).

The window title must contain a "[*]" placeholder, which indicates where the '*' should appear. Normally, it should appear right after the file name (e.g., "document1.txt[*] - Text Editor"). If the window isn't modified, the placeholder is simply removed.

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.

访问函数:

bool isWindowModified () const
void setWindowModified ( bool )

另请参阅 windowTitle , 应用程序范例 , SDI Example ,和 MDI 范例 .

windowOpacity : double

此特性保持窗口的不透明度级别。

不透明度的有效范围是从 1.0 (完全不透明) 到 0.0 (完全透明)。

默认情况下,此特性的值为 1.0。

This feature is available on Embedded Linux, macOS , Windows, and X11 platforms that support the Composite extension.

注意: 在 X11,需要运行复合管理器,且 X11 的特定 _NET_WM_WINDOW_OPACITY 原子需要所用窗口管理器的支持。

警告: 把此特性从不透明更改为透明可能发生,在窗口被正确显示之前需要处理的描绘事件。这主要影响 QPixmap::grabWindow() 的使用。另请注意:半透明窗口的更新和大小调整,比不透明窗口明显更慢。

访问函数:

qreal windowOpacity () const
void setWindowOpacity (qreal level )

另请参阅 setMask ().

windowTitle : QString

此特性保持窗口标题 (Caption 题注)

此特性仅对顶层 Widget (譬如:窗口和对话框) 有意义。若未设置 Caption (题注),则标题基于 windowFilePath 。若都未设置,则标题为空字符串。

若使用 windowModified mechanism, the window title must contain a "[*]" placeholder, which indicates where the '*' should appear. Normally, it should appear right after the file name (e.g., "document1.txt[*] - Text Editor"). If the windowModified 特性为 false (默认),占位符会被简单移除。

在某些桌面平台 (包括 Windows 和 Unix),应用程序名称 (来自 QGuiApplication::applicationDisplayName ) is added at the end of the window title, if set. This is done by the QPA plugin, so it is shown to the user, but isn't part of the windowTitle string.

访问函数:

QString windowTitle () const
void setWindowTitle ( const QString & )

通知信号:

void windowTitleChanged (const QString & title )

另请参阅 windowIcon , windowModified ,和 windowFilePath .

x : const int

此特性保持 Widget 相对于其父级 (包括任何窗框) 的 X 坐标

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

默认情况下,此特性拥有 0 值。

访问函数:

int x () const

另请参阅 frameGeometry , y ,和 pos .

y : const int

此特性保持 Widget 相对于其父级和包括任何窗框的 y 坐标

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

默认情况下,此特性拥有 0 值。

访问函数:

int y () const

另请参阅 frameGeometry , x ,和 pos .

成员函数文档编制

QWidget:: QWidget ( QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags())

构造子级 Widget 为 parent ,采用 Widget 设置标志 f .

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.

Widget 标志自变量 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 .

If you add a child widget to an already visible widget you must explicitly show the child to make it visible.

Note that the X11 version of Qt may not be able to deliver all combinations of style flags on all systems. This is because on X11, Qt can only ask the window manager, and the window manager can override the application's settings. On Windows, Qt can set whatever flags you want.

另请参阅 windowFlags .

[virtual] QWidget:: ~QWidget ()

销毁 Widget。

此 Widget 的所有子级被首先删除。退出应用程序若此 Widget 是主小部件。

[virtual protected] void QWidget:: actionEvent ( QActionEvent * event )

此事件处理程序被调用采用给定 event 每当 Widget 的操作发生更改时。

另请参阅 addAction (), insertAction (), removeAction (), actions (),和 QActionEvent .

QList < QAction *> QWidget:: actions () const

返回此 Widget 的动作列表 (可能为空)。

另请参阅 contextMenuPolicy , insertAction (),和 removeAction ().

void QWidget:: activateWindow ()

把包含此 Widget 的顶层 Widget,设为活动窗口。

活动窗口是具有键盘输入聚焦的可见顶层窗口。

此函数履行如在顶层窗口的标题栏上,点击鼠标的相同操作。在 X11,结果取决于窗口管理器。若想要确保窗口堆叠在顶部,同样,还应调用 raise ()。注意:窗口必须可见,否则 activateWindow() 无效。

在 Windows,若在应用程序目前不是活动窗口时调用这,则不会使其成为活动窗口。它会改变任务栏条目的颜色,以指示窗口在某些方面有变化。这是因为 Microsoft 不允许应用程序,去中断用户在另一应用程序中目前正做的。

另请参阅 isActiveWindow (), window (), show (),和 QWindowsWindowFunctions::setWindowActivationBehavior ().

void QWidget:: addAction ( QAction * action )

追加动作 action 到此 Widget 的动作列表。

所有 QWidget 都有列表,针对 QAction ,无论如何,可以按多种不同方式图形表示它们。默认使用 QAction 列表 (返回通过 actions ()) 创建上下文 QMenu .

A QWidget 只应每动作有一个,且已添加动作不会导致同一动作在 Widget 中出现两次。

The ownership of action 不会被转移给此 QWidget .

另请参阅 removeAction (), insertAction (), actions (),和 QMenu .

void QWidget:: addActions ( QList < QAction *> actions )

追加动作 actions 到此 Widget 的动作列表。

另请参阅 removeAction (), QMenu ,和 addAction ().

void QWidget:: adjustSize ()

调整 Widget 大小,以拟合其内容。

此函数使用 sizeHint () if it is valid, i.e., the size hint's width and height are >= 0. Otherwise, it 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. If the sizeHint () is less than (200, 100) and the size policy is expanding , the window will be at least (200, 100). The maximum size of a window is 2/3 of the screen's width and height.

另请参阅 sizeHint () 和 childrenRect ().

QPalette::ColorRole QWidget:: backgroundRole () const

返回 Widget 的背景角色。

The background role defines the brush from the widget's palette that is used to render the background.

If no explicit background role is set, the widget inherts its parent widget's background role.

另请参阅 setBackgroundRole () 和 foregroundRole ().

QBackingStore *QWidget:: backingStore () const

返回 QBackingStore this widget will be drawn into.

This function was introduced in Qt 5.0.

[virtual protected] void QWidget:: changeEvent ( QEvent * event )

此事件处理程序可以被重实现以处理状态改变。

在此事件中改变的状态可以被检索透过 event 供给。

改变事件包括: 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 , QEvent::ReadOnlyChange .

QWidget *QWidget:: childAt ( int x , int y ) const

Returns the visible child widget at the position ( x , y ) in the widget's coordinate system. If there is no visible child widget at the specified position, the function returns nullptr .

QWidget *QWidget:: childAt (const QPoint & p ) const

这是重载函数。

Returns the visible child widget at point p in the widget's own coordinate system.

void QWidget:: clearFocus ()

从 Widget 获取键盘输入聚焦。

若 Widget 有活动聚焦, 聚焦出事件 被发送给此 Widget 以告诉它已丢失聚焦。

此 Widget 必须启用聚焦设置以获取键盘输入聚焦,即:它必须调用 setFocusPolicy ().

另请参阅 hasFocus (), setFocus (), focusInEvent (), focusOutEvent (), setFocusPolicy (),和 QApplication::focusWidget ().

void QWidget:: clearMask ()

移除任何遮罩设置通过 setMask ().

另请参阅 setMask ().

[slot] bool QWidget:: close ()

关闭此 Widget。返回 true 若 Widget 被关闭;否则返回 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. A close events is delivered to the widget no matter if the widget is visible or not.

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. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.

[virtual protected] void QWidget:: closeEvent ( QCloseEvent * event )

此事件处理程序被调用采用给定 event when Qt receives a window close request for a top-level widget from the window system.

By default, the event is accepted and the widget is closed. You can reimplement this function to change the way the widget responds to window close requests. For example, you can prevent the window from closing by calling ignore() on all events.

Main window applications typically use reimplementations of this function to check whether the user's work has been saved and ask for permission before closing. For example, the 应用程序范例 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();
    }
}
							

另请参阅 event (), hide (), close (), QCloseEvent ,和 应用程序范例 .

QMargins QWidget:: contentsMargins () const

The contentsMargins function returns the widget's contents margins.

This function was introduced in Qt 4.6.

另请参阅 getContentsMargins (), setContentsMargins (),和 contentsRect ().

QRect QWidget:: contentsRect () const

Returns the area inside the widget's margins.

另请参阅 setContentsMargins () 和 getContentsMargins ().

[virtual protected] void QWidget:: contextMenuEvent ( QContextMenuEvent * event )

此事件处理程序对于事件 event ,可以在子类中被重实现以接收 Widget 上下文菜单事件。

处理程序被调用,当 Widget 的 contextMenuPolicy is Qt::DefaultContextMenu .

默认实现忽略上下文事件。见 QContextMenuEvent 文档编制了解更多细节。

另请参阅 event (), QContextMenuEvent ,和 customContextMenuRequested ().

[protected] void QWidget:: create ( WId window = 0, bool initializeWindow = true, bool destroyOldWindow = true)

创建新 Widget 窗口。

参数 window , initializeWindow ,和 destroyOldWindow 被忽略,在 Qt 5。请使用 QWindow::fromWinId () 去创建 QWindow 包裹外来窗口并把它传递给 QWidget::createWindowContainer () 代替。

另请参阅 createWindowContainer () 和 QWindow::fromWinId ().

[static] QWidget *QWidget:: createWindowContainer ( QWindow * window , QWidget * parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags())

创建 QWidget that makes it possible to embed window into a QWidget -based application.

The window container is created as a child of parent and with window flags flags .

Once the window has been embedded into the container, the container will control the window's geometry and visibility. Explicit calls to QWindow::setGeometry (), QWindow::show () 或 QWindow::hide () on an embedded window is not recommended.

The container takes over ownership of window . The window can be removed from the window container with a call to QWindow::setParent ().

The window container is attached as a native child window to the toplevel window it is a child of. When a window container is used as a child of a QAbstractScrollArea or QMdiArea , it will create a native window for every widget in its parent chain to allow for proper stacking and clipping in this use case. Creating a native window for the window container also allows for proper stacking and clipping. This must be done before showing the window container. Applications with many native child windows may suffer from performance issues.

The window container has a number of known limitations:

  • Stacking order; The embedded window will stack on top of the widget hierarchy as an opaque box. The stacking order of multiple overlapping window container instances is undefined.
  • Rendering Integration; The window container does not interoperate with QGraphicsProxyWidget , QWidget::render () or similar functionality.
  • Focus Handling; It is possible to let the window container instance have any focus policy and it will delegate focus to the window via a call to QWindow::requestActivate (). However, returning to the normal focus chain from the QWindow instance will be up to the QWindow instance implementation itself. For instance, when entering a Qt Quick based window with tab focus, it is quite likely that further tab presses will only cycle inside the QML application. Also, whether QWindow::requestActivate () actually gives the window focus, is platform dependent.
  • Using many window container instances in a QWidget -based application can greatly hurt the overall performance of the application.

[signal] void QWidget:: customContextMenuRequested (const QPoint & pos )

此信号被发射当 Widget 的 contextMenuPolicy is Qt::CustomContextMenu ,且用户已请求 Widget 的上下文菜单。位置 pos 是 Widget 接收上下文菜单事件的位置。通常,这在 Widget 坐标中。此规则的例外是 QAbstractScrollArea 且其子类把上下文菜单事件映射到坐标为 viewport() .

另请参阅 mapToGlobal (), QMenu ,和 contextMenuPolicy .

[protected] void QWidget:: destroy ( bool destroyWindow = true, bool destroySubWindows = true)

释放窗口系统资源。销毁 Widget 窗口,若 destroyWindow 为 true。

destroy() 会为所有子级 Widget 递归调用本身,传递 destroySubWindows destroyWindow 参数。要更好地控制 Subwidget 的销毁,请先选择性地销毁 Subwidget。

此函数通常被调用从 QWidget 析构函数。

[virtual protected] void QWidget:: dragEnterEvent ( QDragEnterEvent * event )

This event handler is called when a drag is in progress and the mouse enters this widget. The event is passed in the event 参数。

If the event is ignored, the widget won't receive any drag move events .

Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

另请参阅 QDrag and QDragEnterEvent .

[virtual protected] void QWidget:: dragLeaveEvent ( QDragLeaveEvent * event )

This event handler is called when a drag is in progress and the mouse leaves this widget. The event is passed in the event 参数。

Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

另请参阅 QDrag and QDragLeaveEvent .

[virtual protected] void QWidget:: dragMoveEvent ( QDragMoveEvent * event )

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 参数。

Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

另请参阅 QDrag and QDragMoveEvent .

[virtual protected] void QWidget:: dropEvent ( QDropEvent * event )

This event handler is called when the drag is dropped on this widget. The event is passed in the event 参数。

Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

另请参阅 QDrag and QDropEvent .

WId QWidget:: effectiveWinId () const

返回 Widget 的有效窗口系统标识符,即:本机父级的窗口系统标识符。

If the widget is native, this function returns the native widget ID. Otherwise, the window ID of the first native parent widget, i.e., the top-level widget that contains this widget, is returned.

注意: We recommend that you do not store this value as it is likely to change at run-time.

This function was introduced in Qt 4.4.

另请参阅 nativeParentWidget ().

void QWidget:: ensurePolished () const

确保 Widget 及其子级已被抛光,通过 QStyle (即:拥有恰当的字体和调色板)。

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.

注意: The function is declared const so that it can be called from other const functions (e.g., sizeHint ()).

另请参阅 event ().

[virtual protected] void QWidget:: enterEvent ( QEvent * event )

此事件处理程序可以在子类中被重实现以接收 Widget 进入事件,被传入 event 参数。

事件被发送给 Widget,当鼠标光标进入 Widget 时。

另请参阅 leaveEvent (), mouseMoveEvent (),和 event ().

[override virtual protected] bool QWidget:: event ( QEvent * event )

Reimplemented from QObject::event ().

这是主事件处理程序;它处理事件 event 。可以在子类中重实现此函数,但推荐使用某一专用事件处理程序代替。

按键和释放事件的处理不同于其它事件。event() 检查 Tab 和 Shift+Tab 并试着适当移动聚焦。若没有能移动聚焦的 Widget (或按键不是 Tab 或 Shift+Tab),event() 调用 keyPressEvent ().

鼠标和平板事件的处理也有点特殊:仅当 Widget enabled ,event() 会调用专用处理程序,譬如 mousePressEvent ();否则它会丢弃事件。

此函数返回 true 若事件被识别,否则它返回 false 。若识别事件被接受 (见 QEvent::accepted ),任何进一步的处理 (譬如:把事件传播给父级 Widget) 都会停止。

另请参阅 closeEvent (), focusInEvent (), focusOutEvent (), enterEvent (), keyPressEvent (), keyReleaseEvent (), leaveEvent (), mouseDoubleClickEvent (), mouseMoveEvent (), mousePressEvent (), mouseReleaseEvent (), moveEvent (), paintEvent (), resizeEvent (), QObject::event (),和 QObject::timerEvent ().

[static] QWidget *QWidget:: find ( WId id )

返回指向 Widget 的指针,采用窗口标识符/句柄 id .

窗口标识符类型取决于底层窗口系统,见 qwindowdefs.h for the actual definition. If there is no widget with this identifier, 0 is returned.

[virtual protected] void QWidget:: focusInEvent ( QFocusEvent * event )

此事件处理程序可以在子类中被重实现,以接收 Widget 的键盘聚焦事件 (聚焦接收)。事件被传入 event parameter

Widget 通常必须 setFocusPolicy () 到某物除了 Qt::NoFocus in order to receive focus events. (Note that the application programmer can call setFocus () 在任何 Widget,即使其通常不接受聚焦。)

默认实现更新 Widget (除了窗口未指定 focusPolicy ()).

另请参阅 focusOutEvent (), setFocusPolicy (), keyPressEvent (), keyReleaseEvent (), event (),和 QFocusEvent .

[protected] bool QWidget:: focusNextChild ()

查找新的 Widget 以给予键盘聚焦,如适合 Tab ,并返回 true 若能找到新的 Widget,或 false 若找不到。

另请参阅 focusPreviousChild ().

[virtual protected] bool QWidget:: focusNextPrevChild ( bool next )

查找新的 Widget 以给予键盘聚焦,如适合 Tab 和 Shift+Tab,并返回 true 若能找到新的 Widget,或 false 若找不到。

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".

Child widgets call focusNextPrevChild() on their parent widgets, but only the window that contains the child widgets decides where to redirect focus. By reimplementing this function for an object, you thus gain control of focus traversal for all child widgets.

另请参阅 focusNextChild () 和 focusPreviousChild ().

[virtual protected] void QWidget:: focusOutEvent ( QFocusEvent * event )

此事件处理程序可以在子类中被重实现,以接收 Widget 的键盘聚焦事件 (聚焦丢失)。事件被传入 event 参数。

Widget 通常必须 setFocusPolicy () 到某物除了 Qt::NoFocus in order to receive focus events. (Note that the application programmer can call setFocus () 在任何 Widget,即使其通常不接受聚焦。)

默认实现更新 Widget (除了窗口未指定 focusPolicy ()).

另请参阅 focusInEvent (), setFocusPolicy (), keyPressEvent (), keyReleaseEvent (), event (),和 QFocusEvent .

[protected] bool QWidget:: focusPreviousChild ()

查找新的 Widget 以给予键盘聚焦,如适合 Shift+Tab ,并返回 true 若能找到新的 Widget,或 false 若找不到。

另请参阅 focusNextChild ().

QWidget *QWidget:: focusProxy () const

Returns the focus proxy, or 0 if there is no focus proxy.

另请参阅 setFocusProxy ().

QWidget *QWidget:: focusWidget () const

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.

QFontInfo QWidget:: fontInfo () const

Returns the font info for the widget's current font. Equivalent to QFontInfo(widget->font()) .

另请参阅 font (), fontMetrics (),和 setFont ().

QFontMetrics QWidget:: fontMetrics () const

Returns the font metrics for the widget's current font. Equivalent to QFontMetrics(widget->font()) .

另请参阅 font (), fontInfo (),和 setFont ().

QPalette::ColorRole QWidget:: foregroundRole () const

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.

另请参阅 setForegroundRole () 和 backgroundRole ().

void QWidget:: getContentsMargins ( int * left , int * top , int * right , int * bottom ) const

Returns the widget's contents margins for left , top , right ,和 bottom .

另请参阅 setContentsMargins () 和 contentsRect ().

QPixmap QWidget:: grab (const QRect & rectangle = QRect(QPoint(0, 0), QSize(-1, -1)))

把 Widget 渲染成像素图,约束通过给定 rectangle 。若 Widget 有任何子级,它们也会被描绘在适当位置。

若矩形具有无效指定尺寸 (默认),整个 Widget 被描绘。

This function was introduced in Qt 5.0.

注意: 此函数可以被援引,通过元对象系统和从 QML。见 Q_INVOKABLE .

另请参阅 render () 和 QPixmap .

void QWidget:: grabGesture ( Qt::GestureType gesture , Qt::GestureFlags flags = Qt::GestureFlags())

将 Widget 订阅到给定 gesture 采有特定 flags .

This function was introduced in Qt 4.6.

另请参阅 ungrabGesture () 和 QGestureEvent .

void QWidget:: grabKeyboard ()

抓取键盘输入。

此 Widget 接收所有键盘事件直到 releaseKeyboard () 被调用;其它 Widget 根本没有键盘事件。鼠标事件不受影响。使用 grabMouse () 若希望抓取。

聚焦 Widget 不受影响,除了它不接收任何键盘事件。 setFocus () 照常移动聚焦,但新聚焦 Widget 接收键盘事件,仅在 releaseKeyboard () 被调用。

如果另一 Widget 目前正在抓取键盘输入,则会先释放该 Widget 的抓取。

另请参阅 releaseKeyboard (), grabMouse (), releaseMouse (),和 focusWidget ().

void QWidget:: grabMouse ()

抓取鼠标输入。

此 Widget 接收所有鼠标事件直到 releaseMouse () 被调用;其它 Widget 根本没有鼠标事件。键盘事件不受影响。使用 grabKeyboard () 若希望抓取。

警告: 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.

注意: Only visible widgets can grab mouse input. If isVisible () 返回 false for a widget, that widget cannot call grabMouse().

注意: On Windows, grabMouse() only works when the mouse is inside a window owned by the process. On macOS , grabMouse() only works when the mouse is inside the frame of that widget.

另请参阅 releaseMouse (), grabKeyboard (),和 releaseKeyboard ().

void QWidget:: grabMouse (const QCursor & cursor )

This function overloads grabMouse ().

抓取鼠标输入和改变光标形状。

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().

警告: 抓取鼠标可能锁定终端。

注意: See the note in QWidget::grabMouse ().

另请参阅 releaseMouse (), grabKeyboard (), releaseKeyboard (),和 setCursor ().

int QWidget:: grabShortcut (const QKeySequence & key , Qt::ShortcutContext context = Qt::WindowShortcut)

Adds a shortcut to Qt's shortcut system that watches for the given key sequence in the given context 。若 context is Qt::ApplicationShortcut , the shortcut applies to the application as a whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut , or to the window itself, 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.

警告: You should not normally need to use this function; instead create QAction s with the shortcut key sequences you require (if you also want equivalent menu options and toolbar buttons), or create QShortcut s if you just need key sequences. Both QAction and QShortcut handle all the event filtering for you, and provide signals which are triggered when the user triggers the key sequence, so are much easier to use than this low-level function.

另请参阅 releaseShortcut () 和 setShortcutEnabled ().

QGraphicsEffect *QWidget:: graphicsEffect () const

graphicsEffect 函数返回指向 Widget 图形效果的指针。

If the widget has no graphics effect, 0 is returned.

This function was introduced in Qt 4.6.

另请参阅 setGraphicsEffect ().

QGraphicsProxyWidget *QWidget:: graphicsProxyWidget () const

Returns the proxy widget for the corresponding embedded widget in a graphics view; otherwise returns nullptr .

This function was introduced in Qt 4.5.

另请参阅 QGraphicsProxyWidget::createProxyForChildWidget () 和 QGraphicsScene::addWidget ().

bool QWidget:: hasEditFocus () const

返回 true if this widget currently has edit focus; otherwise false.

This feature is only available in Qt for Embedded Linux.

另请参阅 setEditFocus () 和 QApplication::keypadNavigationEnabled ().

[virtual] bool QWidget:: hasHeightForWidth () const

返回 true if the widget's preferred height depends on its width; otherwise returns false .

This function was introduced in Qt 5.0.

[virtual] int QWidget:: heightForWidth ( int w ) const

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.

[slot] void QWidget:: hide ()

隐藏 Widget。此函数相当于 setVisible (false).

注意: 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.

另请参阅 hideEvent (), isHidden (), show (), setVisible (), isVisible (),和 close ().

[virtual protected] void QWidget:: hideEvent ( QHideEvent * event )

This event handler can be reimplemented in a subclass to receive widget hide events. The event is passed in the event 参数。

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 ().

另请参阅 visible , event (),和 QHideEvent .

[override virtual protected] void QWidget:: initPainter ( QPainter * painter ) const

初始化 painter 钢笔,背景和字体与给定 Widget 的相同。自动调用此函数,当描绘器被打开在 QWidget .

[virtual protected] void QWidget:: inputMethodEvent ( QInputMethodEvent * event )

此事件处理程序对于事件 event ,可以在子类中重实现以接收输入法合成事件。处理程序被调用,当输入法状态改变时。

注意:当创建自定义文本编辑 Widget 时, Qt::WA_InputMethodEnabled 窗口属性必须被明确设置 (使用 setAttribute () 函数) 为接收输入法事件。

默认实现调用 event->ignore(),拒绝输入法事件。见 QInputMethodEvent 文档编制了解更多细节。

另请参阅 event () 和 QInputMethodEvent .

[virtual] QVariant QWidget:: inputMethodQuery ( Qt::InputMethodQuery query ) const

此方法仅与输入 Widget 相关。输入法使用它查询 Widget 的一组属性,以便能够支持为支持围绕文本和再转换的复杂输入法操作。

query 指定要查询的特性。

另请参阅 inputMethodEvent (), QInputMethodEvent , QInputMethodQueryEvent ,和 inputMethodHints .

void QWidget:: insertAction ( QAction * before , QAction * action )

插入动作 action 到此 Widget 的动作列表,前置于动作 before 。它追加动作,若 before is 0 or before 不是有效动作 (对于此 Widget)。

A QWidget 每动作只应有一个。

另请参阅 removeAction (), addAction (), QMenu , contextMenuPolicy ,和 actions ().

void QWidget:: insertActions ( QAction * before , QList < QAction *> actions )

插入动作 actions 到此 Widget 的动作列表,前置于动作 before 。它追加动作,若 before is 0 or before 不是有效动作 (对于此 Widget)。

A QWidget 每动作最多能有一个。

另请参阅 removeAction (), QMenu , insertAction (),和 contextMenuPolicy .

bool QWidget:: isAncestorOf (const QWidget * child ) const

返回 true 若此 Widget 是父级 (或祖父级等任何级别),针对给定 child ,且两 Widget 在同一窗口;否则返回 false .

bool QWidget:: isEnabledTo (const QWidget * ancestor ) const

返回 true 若此 Widget 将变为被启用,若 ancestor 被启用;否则返回 false .

This is the case if neither the widget itself nor every parent up to but excluding ancestor has been explicitly disabled.

isEnabledTo(0) returns false if this widget or any if its ancestors was explicitly disabled.

The word ancestor here means a parent widget within the same window.

Therefore isEnabledTo(0) stops at this widget's window, unlike isEnabled () which also takes parent windows into considerations.

另请参阅 setEnabled () 和 enabled .

bool QWidget:: isHidden () const

返回 true 若 Widget 被隐藏,否则返回 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 visibility, 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.

Widget 被隐藏,若:

  • they were created as independent windows,
  • they were created as children of visible widgets,
  • hide () 或 setVisible (false) was called.

bool QWidget:: isVisibleTo (const QWidget * ancestor ) const

返回 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 ().

另请参阅 show (), hide (),和 isVisible ().

bool QWidget:: isWindow () const

返回 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 标志。

另请参阅 window (), isModal (),和 parentWidget ().

[virtual protected] void QWidget:: keyPressEvent ( QKeyEvent * event )

此事件处理程序对于事件 event ,可以在子类中重实现以接收 Widget 的按键事件。

widget 必须调用 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 the key sequence for QKeySequence::Cancel (typically the Escape key). Otherwise the event is ignored, so that the widget's parent can interpret it.

注意: 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.

另请参阅 keyReleaseEvent (), setFocusPolicy (), focusInEvent (), focusOutEvent (), event (), QKeyEvent ,和 Tetrix Example .

[virtual protected] void QWidget:: keyReleaseEvent ( QKeyEvent * 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.

注意: 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.

另请参阅 keyPressEvent (), QEvent::ignore (), setFocusPolicy (), focusInEvent (), focusOutEvent (), event (),和 QKeyEvent .

[static] QWidget *QWidget:: keyboardGrabber ()

返回目前正抓取键盘输入的 Widget。

If no widget in this application is currently grabbing the keyboard, 0 is returned.

另请参阅 grabMouse () 和 mouseGrabber ().

QLayout *QWidget:: layout () const

Returns the layout manager that is installed on this widget, or 0 if no layout manager is installed.

布局管理器设置已被添加到布局的 Widget 子级的几何体。

另请参阅 setLayout (), sizePolicy (),和 布局管理 .

[virtual protected] void QWidget:: leaveEvent ( QEvent * event )

This event handler can be reimplemented in a subclass to receive widget leave events which are passed in the event 参数。

A leave event is sent to the widget when the mouse cursor leaves the widget.

另请参阅 enterEvent (), mouseMoveEvent (),和 event ().

[slot] void QWidget:: lower ()

把 Widget 降低到父级 Widget 的堆栈底部。

After this call the widget will be visually behind (and therefore obscured by) any overlapping sibling widgets.

另请参阅 raise () 和 stackUnder ().

QPoint QWidget:: mapFrom (const QWidget * parent , const QPoint & pos ) const

翻译 Widget 坐标 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.

另请参阅 mapTo (), mapFromParent (), mapFromGlobal (),和 underMouse ().

QPoint QWidget:: mapFromGlobal (const QPoint & pos ) const

翻译全局屏幕坐标 pos 到 Widget 坐标。

另请参阅 mapToGlobal (), mapFrom (),和 mapFromParent ().

QPoint QWidget:: mapFromParent (const QPoint & pos ) const

翻译父级 Widget 坐标 pos 到 Widget 坐标。

如同 mapFromGlobal () 若 Widget 没有父级。

另请参阅 mapToParent (), mapFrom (), mapFromGlobal (),和 underMouse ().

QPoint QWidget:: mapTo (const QWidget * parent , const QPoint & pos ) const

翻译 Widget 坐标 pos parent coordinate system. The parent must not be 0 and must be a parent of the calling widget.

另请参阅 mapFrom (), mapToParent (), mapToGlobal (),和 underMouse ().

QPoint QWidget:: mapToGlobal (const QPoint & pos ) const

翻译 Widget 坐标 pos 到全局屏幕坐标。例如: mapToGlobal(QPoint(0,0)) 将给出 Widget 左上像素的全局坐标。

另请参阅 mapFromGlobal (), mapTo (),和 mapToParent ().

QPoint QWidget:: mapToParent (const QPoint & pos ) const

翻译 Widget 坐标 pos 到父级 Widget 坐标。

如同 mapToGlobal () 若 Widget 没有父级。

另请参阅 mapFromParent (), mapTo (), mapToGlobal (),和 underMouse ().

QRegion QWidget:: mask () const

返回在 Widget 上目前设置的遮罩。若未设置遮罩,返回值会是空区域。

另请参阅 setMask (), clearMask (), QRegion::isEmpty (),和 异形时钟范例 .

[override virtual protected] int QWidget:: metric ( QPaintDevice::PaintDeviceMetric m ) const

Reimplemented from QPaintDevice::metric ().

Internal implementation of the virtual QPaintDevice::metric () 函数。

m is the metric to get.

[virtual protected] void QWidget:: mouseDoubleClickEvent ( QMouseEvent * event )

此事件处理程序对于事件 event , can be reimplemented in a subclass to receive mouse double click events for the widget.

默认实现调用 mousePressEvent ().

注意: The widget will also receive mouse press and mouse release events in addition to the double click event. It is up to the developer to ensure that the application interprets these events correctly.

另请参阅 mousePressEvent (), mouseReleaseEvent (), mouseMoveEvent (), event (),和 QMouseEvent .

[static] QWidget *QWidget:: mouseGrabber ()

返回目前正抓取鼠标输入的 Widget。

If no widget in this application is currently grabbing the mouse, 0 is returned.

另请参阅 grabMouse () 和 keyboardGrabber ().

[virtual protected] void QWidget:: mouseMoveEvent ( QMouseEvent * 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.

If you want to show a tooltip immediately, while the mouse is moving (e.g., to get the mouse coordinates with QMouseEvent::pos () and show them as a tooltip), you must first enable mouse tracking as described above. Then, to ensure that the tooltip is updated immediately, you must call QToolTip::showText () instead of setToolTip () in your implementation of mouseMoveEvent().

另请参阅 setMouseTracking (), mousePressEvent (), mouseReleaseEvent (), mouseDoubleClickEvent (), event (), QMouseEvent ,和 涂鸦范例 .

[virtual protected] void QWidget:: mousePressEvent ( QMouseEvent * event )

此事件处理程序对于事件 event ,可以在子类中被重实现以接收 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.

另请参阅 mouseReleaseEvent (), mouseDoubleClickEvent (), mouseMoveEvent (), event (), QMouseEvent ,和 涂鸦范例 .

[virtual protected] void QWidget:: mouseReleaseEvent ( QMouseEvent * event )

此事件处理程序对于事件 event ,可以在子类中被重实现以接收 Widget 的鼠标释放事件。

另请参阅 mousePressEvent (), mouseDoubleClickEvent (), mouseMoveEvent (), event (), QMouseEvent ,和 涂鸦范例 .

void QWidget:: move ( int x , int y )

这是重载函数。

这相当于 move( QPoint ( x , y )).

注意: Setter 函数为特性 pos .

[virtual protected] void QWidget:: moveEvent ( QMoveEvent * event )

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 ().

另请参阅 resizeEvent (), event (), move (),和 QMoveEvent .

[virtual protected] bool QWidget:: nativeEvent (const QByteArray & eventType , void * message , long * result )

This special event handler can be reimplemented in a subclass to receive native platform events identified by eventType which are passed in the message 参数。

In your reimplementation of this function, if you want to stop the event being handled by Qt, return true and set result result parameter has meaning only on Windows. 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.

注意: 事件才会被交付给此事件处理程序,若 Widget 具有本机窗口句柄。

注意: 此函数取代 Qt 4 的事件过滤器函数 x11Event() winEvent() 及 macEvent()。

平台 事件类型标识符 消息类型 结果类型
Windows "windows_generic_MSG" MSG * LRESULT
macOS "NSEvent" NSEvent *
XCB "xcb_generic_event_t" xcb_generic_event_t *

另请参阅 QAbstractNativeEventFilter .

QWidget *QWidget:: nativeParentWidget () const

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.

This function was introduced in Qt 4.4.

另请参阅 effectiveWinId ().

QWidget *QWidget:: nextInFocusChain () const

Returns the next widget in this widget's focus chain.

另请参阅 previousInFocusChain ().

void QWidget:: overrideWindowFlags ( Qt::WindowFlags flags )

Sets the window flags for the widget to flags , without telling the window system.

警告: Do not call this function unless you really know what you're doing.

另请参阅 setWindowFlags ().

[override virtual] QPaintEngine *QWidget:: paintEngine () const

Reimplemented from QPaintDevice::paintEngine ().

返回 Widget 的描绘引擎。

Note that this function should not be called explicitly by the user, since it's meant for reimplementation purposes only. The function is called by Qt internally, and the default implementation may not always return a valid pointer.

[virtual protected] void QWidget:: paintEvent ( QPaintEvent * event )

此事件处理程序可在子类中被重实现,以接收传入描绘事件 event .

描绘事件是重新描绘 Widget 全部或局部的请求。它能发生是因为下列原因之一:

  • repaint () 或 update () 被援引,
  • Widget 被遮盖且现被发现,或
  • 许多其它原因。

许多 Widget 可以在被要求时仅重新描绘其整个表面,但一些缓慢 Widget 需要通过只描绘请求区域进行优化: QPaintEvent::region ()。此速度优化不改变结果,因为描绘会被裁剪到该区域 (在事件处理期间)。 QListView and QTableView 会这样做,例如。

Qt 还试着通过把多个描绘事件合并成一个以加速描绘。当 update () 被多次调用或窗口系统发送多个描绘事件,Qt 把这些事件合并成具有更大区域的一个事件 (见 QRegion::united ())。 repaint () 函数不准许进行此种优化,因此建议使用 update () 每当可能时。

当描绘事件发生时,更新区域通常已被擦除,因此您正在 Widget 的背景上描绘。

背景可以被设置使用 setBackgroundRole () 和 setPalette ().

从 Qt 4.0 起, QWidget 自动双缓冲其描绘,因此不需要在 paintEvent() 中编写双缓冲代码以避免闪烁。

注意: 通常,应该克制调用 update () 或 repaint () inside paintEvent()。例如,调用 update () 或 repaint () 在 paintEvent() 内子级会导致未定义行为;子级可能 (或不可能) 获得描绘事件。

警告: 若正在使用没有 Qt 的 Backingstore (后备存储) 的自定义描绘引擎, Qt::WA_PaintOnScreen 必须被设置。否则, QWidget::paintEngine () 将从不被调用;代之,将使用 Backingstore (后备存储)。

另请参阅 event (), repaint (), update (), QPainter , QPixmap , QPaintEvent ,和 指针式时钟范例 .

QWidget *QWidget:: parentWidget () const

Returns the parent of this widget, or 0 if it does not have any parent widget.

QWidget *QWidget:: previousInFocusChain () const

The previousInFocusChain function returns the previous widget in this widget's focus chain.

This function was introduced in Qt 4.6.

另请参阅 nextInFocusChain ().

[slot] void QWidget:: raise ()

把此 Widget 提升到父级 Widget 的堆栈顶部。

在此调用之后,Widget 会在任何重叠同级 Widget 之前可见。

注意: 当使用 activateWindow (),可以调用此函数以确保窗口堆叠在顶部。

另请参阅 lower () 和 stackUnder ().

void QWidget:: releaseKeyboard ()

释放键盘抓取。

另请参阅 grabKeyboard (), grabMouse (),和 releaseMouse ().

void QWidget:: releaseMouse ()

释放鼠标抓取。

另请参阅 grabMouse (), grabKeyboard (),和 releaseKeyboard ().

void QWidget:: releaseShortcut ( int id )

Removes the shortcut with the given id from Qt's shortcut system. The widget will no longer receive QEvent::Shortcut events for the shortcut's key sequence (unless it has other shortcuts with the same key sequence).

警告: You should not normally need to use this function since Qt's shortcut system removes shortcuts automatically when their parent widget is destroyed. It is best to use QAction or QShortcut to handle shortcuts, since they are easier to use than this low-level function. Note also that this is an expensive operation.

另请参阅 grabShortcut () 和 setShortcutEnabled ().

void QWidget:: removeAction ( QAction * action )

移除动作 action 从此 Widget 的动作列表。

另请参阅 insertAction (), actions (),和 insertAction ().

void QWidget:: render ( QPaintDevice * target , const QPoint & targetOffset = QPoint(), const QRegion & sourceRegion = QRegion(), QWidget::RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren))

渲染 sourceRegion of this widget into the target 使用 renderFlags to determine how to render. Rendering starts at targetOffset target . For example:

QPixmap pixmap(widget->size());
widget->render(&pixmap);
							

sourceRegion is a null region, this function will use QWidget::rect () as the region, i.e. the entire widget.

Ensure that you call QPainter::end () for the target device's active painter (if any) before rendering. For example:

QPainter painter(this);
...
painter.end();
myWidget->render(this);
							

注意: To obtain the contents of a QOpenGLWidget ,使用 QOpenGLWidget::grabFramebuffer () 代替。

注意: To obtain the contents of a QGLWidget (deprecated), use QGLWidget::grabFrameBuffer() or QGLWidget::renderPixmap() instead.

This function was introduced in Qt 4.3.

void QWidget:: render ( QPainter * painter , const QPoint & targetOffset = QPoint(), const QRegion & sourceRegion = QRegion(), QWidget::RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren))

这是重载函数。

Renders the widget into the painter 's QPainter::device ().

Transformations and settings applied to the painter will be used when rendering.

注意: painter must be active. On macOS the widget will be rendered into a QPixmap and then drawn by the painter .

另请参阅 QPainter::device ().

[slot] void QWidget:: repaint ()

直接重新绘制 Widget 通过调用 paintEvent () 立即,除非更新被禁用或 Widget 被隐藏。

我们建议仅在需要立即重新绘制 (如:在动画期间) 时才使用 repaint()。在几乎所有情况下 update () 更好,因为它准许 Qt 优化速度并最小化闪烁。

警告: 若在可以调用本身的函数中调用 repaint() 从 paintEvent (),可能获得无限递归。 update () 函数从不导致递归。

另请参阅 update (), paintEvent (),和 setUpdatesEnabled ().

void QWidget:: repaint ( int x , int y , int w , int h )

这是重载函数。

此版本重新描绘矩形 ( x , y , w , h ) 在 Widget 内。

w 是负的,它会被替换采用 width() - x ,且若 h 是负的,它会被替换采用 height() - y .

void QWidget:: repaint (const QRect & rect )

这是重载函数。

此版本重新描绘矩形 rect 在 Widget 内。

void QWidget:: repaint (const QRegion & rgn )

这是重载函数。

此版本重新描绘区域 rgn 在 Widget 内。

void QWidget:: resize ( int w , int h )

这是重载函数。

This corresponds to resize( QSize ( w , h )).

注意: Setter 函数为特性 size .

[virtual protected] void QWidget:: resizeEvent ( QResizeEvent * event )

此事件处理程序可以在子类中被重实现以接收 Widget 重置尺寸事件,被传入 event 参数。当 resizeEvent() 被调用时,Widget 已经有新的几何体。旧尺寸是可访问的透过 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.

另请参阅 moveEvent (), event (), resize (), QResizeEvent , paintEvent (),和 涂鸦范例 .

bool QWidget:: restoreGeometry (const QByteArray & geometry )

Restores the geometry and state of 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 available screen geometry.

To restore geometry saved using QSettings , you can use code like this:

QSettings settings("MyCompany", "MyApp");
myWidget->restoreGeometry(settings.value("myWidget/geometry").toByteArray());
							

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

使用 QMainWindow::restoreState () to restore the geometry and the state of toolbars and dock widgets.

This function was introduced in Qt 4.2.

另请参阅 saveGeometry (), QSettings , QMainWindow::saveState (),和 QMainWindow::restoreState ().

QByteArray QWidget:: saveGeometry () const

Saves the current geometry and state for top-level widgets.

To save the geometry when the window closes, you can implement a close event like this:

void MyWidget::closeEvent(QCloseEvent *event)
{
    QSettings settings("MyCompany", "MyApp");
    settings.setValue("geometry", saveGeometry());
    QWidget::closeEvent(event);
}
							

窗口几何体 文档编制,了解有关窗口几何体问题的概述。

使用 QMainWindow::saveState () to save the geometry and the state of toolbars and dock widgets.

This function was introduced in Qt 4.2.

另请参阅 restoreGeometry (), QMainWindow::saveState (),和 QMainWindow::restoreState ().

void QWidget:: scroll ( int dx , int dy )

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.

另请参阅 透明度和双缓冲 .

void QWidget:: scroll ( int dx , int dy , const QRect & r )

这是重载函数。

This version only scrolls r and does not move the children of the widget.

r is empty or invalid, the result is undefined.

另请参阅 QScrollArea .

void QWidget:: setAttribute ( Qt::WidgetAttribute attribute , bool on = true)

设置属性 attribute 在此 Widget 若 on 为 true;否则清零属性。

另请参阅 testAttribute ().

void QWidget:: setBackgroundRole ( QPalette::ColorRole role )

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.

role is QPalette::NoRole , then the widget inherits its parent's background role.

Note that styles are free to choose any color from the palette. You can modify the palette or set a style sheet if you don't achieve the result you want with setBackgroundRole().

另请参阅 backgroundRole () 和 foregroundRole ().

void QWidget:: setBaseSize ( int basew , int baseh )

这是重载函数。

This corresponds to setBaseSize ( QSize ( basew , baseh )). Sets the widgets base size to width basew and height baseh .

注意: Setter 函数为特性 baseSize .

void QWidget:: setContentsMargins ( int left , int top , int right , int bottom )

Sets the margins around the contents of the widget to have the sizes left , top , right ,和 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).

更改边距将触发 resizeEvent ().

另请参阅 contentsMargins (), contentsRect (),和 getContentsMargins ().

void QWidget:: setContentsMargins (const QMargins & margins )

这是重载函数。

setContentsMargins function sets the margins around the widget's contents.

Sets the margins around the contents of the widget to have the sizes determined by margins . 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).

更改边距将触发 resizeEvent ().

This function was introduced in Qt 4.6.

另请参阅 contentsRect () 和 getContentsMargins ().

[slot] void QWidget:: setDisabled ( bool disable )

禁用 Widget 输入事件若 disable 为 true;否则启用输入事件。

enabled 文档编制,了解更多信息。

另请参阅 isEnabledTo (), QKeyEvent , QMouseEvent ,和 changeEvent ().

void QWidget:: setEditFocus ( bool enable )

enable 为 true,使此 Widget 拥有编辑聚焦,在这种情况下 Qt::Key_Up and Qt::Key_Down 通常将被交付给 Widget;否则, Qt::Key_Up and Qt::Key_Down are used to change focus.

This feature is only available in Qt for Embedded Linux.

另请参阅 hasEditFocus () 和 QApplication::keypadNavigationEnabled ().

void QWidget:: setFixedHeight ( int h )

Sets both the minimum and maximum heights of the widget to h without changing the widths. Provided for convenience.

另请参阅 sizeHint (), minimumSize (), maximumSize (),和 setFixedSize ().

void QWidget:: setFixedSize (const QSize & s )

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 .

To remove constraints, set the size to QWIDGETSIZE_MAX .

Alternatively, if you want the widget to have a fixed size based on its contents, you can call QLayout::setSizeConstraint ( QLayout::SetFixedSize );

另请参阅 maximumSize and minimumSize .

void QWidget:: setFixedSize ( int w , int h )

这是重载函数。

把 Widget 的宽度设置为 w 且高度为 h .

void QWidget:: setFixedWidth ( int w )

把 Widget 的最小 最大宽度设为 w 不改变高度。为了方便提供。

另请参阅 sizeHint (), minimumSize (), maximumSize (),和 setFixedSize ().

void QWidget:: setFocus ( Qt::FocusReason reason )

把键盘输入聚焦给予此 Widget (或其聚焦代理),若此 Widget 或其父级之一是 活动窗口 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. If the window is not active, the widget will be given the focus when the window becomes active.

First, a focus about to change event is sent to the focus widget (if any) to tell it that it is about to lose the focus. Then focus is changed, a focus out event is sent to the previous focus item and a focus in event is sent to the new item to tell it that it just received the focus. (Nothing happens if the focus in and focus out widgets are the same.)

注意: On embedded platforms, setFocus () will not cause an input panel to be opened by the input method. If you want this to happen, you have to send a QEvent::RequestSoftwareInputPanel event to the widget yourself.

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.

警告: If you call setFocus () in a function which may itself be called from focusOutEvent () 或 focusInEvent (), you may get an infinite recursion.

另请参阅 hasFocus (), clearFocus (), focusInEvent (), focusOutEvent (), setFocusPolicy (), focusWidget (), QApplication::focusWidget (), grabKeyboard (), grabMouse (), Widget 中的键盘焦点 ,和 QEvent::RequestSoftwareInputPanel .

[slot] void QWidget:: setFocus ()

这是重载函数。

把键盘输入聚焦给予此 Widget (或其聚焦代理),若此 Widget 或其父级之一是 活动窗口 .

void QWidget:: setFocusProxy ( QWidget * w )

把 Widget 的聚焦代理设为小部件 w 。若 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 () 和 hasFocus () operate on the focus proxy.

另请参阅 focusProxy ().

void QWidget:: setForegroundRole ( QPalette::ColorRole role )

把 Widget 的前景角色设为 role .

The foreground role defines the color from the widget's palette that is used to draw the foreground.

role is QPalette::NoRole , the widget uses a foreground role that contrasts with the background role.

Note that styles are free to choose any color from the palette. You can modify the palette or set a style sheet if you don't achieve the result you want with setForegroundRole().

另请参阅 foregroundRole () 和 backgroundRole ().

void QWidget:: setGeometry ( int x , int y , int w , int h )

这是重载函数。

This corresponds to setGeometry ( QRect ( x , y , w , h )).

注意: Setter 函数为特性 geometry .

void QWidget:: setGraphicsEffect ( QGraphicsEffect * effect )

The setGraphicsEffect function is for setting the widget's graphics effect.

effect as the widget's effect. If there already is an effect installed on this widget, QWidget will delete the existing effect before installing the new effect .

effect is the installed effect on a different widget, setGraphicsEffect() will remove the effect from the widget and install it on this widget.

QWidget takes ownership of effect .

注意: This function will apply the effect on itself and all its children.

注意: Graphics effects are not supported for OpenGL-based widgets, such as QGLWidget, QOpenGLWidget and QQuickWidget .

This function was introduced in Qt 4.6.

另请参阅 graphicsEffect ().

[slot] void QWidget:: setHidden ( bool hidden )

便利函数,相当于 setVisible (! hidden ).

另请参阅 isHidden ().

void QWidget:: setLayout ( QLayout * layout )

将此 Widget 的布局管理器设为 layout .

如果此 Widget 已安装了布局管理器, QWidget 是不会允许安装另一个的。必须首先删除现有的布局管理器 (返回通过 layout ()),在可以采用新的布局调用 setLayout() 之前。

layout 是不同 Widget 的布局管理器,setLayout() 将重设父级布局,并使其成为此 Widget 的布局管理器。

范例:

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(formWidget);
    setLayout(layout);
							

调用此函数的备选方案,是把此 Widget 传递给布局构造函数。

QWidget will take ownership of layout .

另请参阅 layout () 和 布局管理 .

void QWidget:: setMask (const QBitmap & bitmap )

促使 Widget 像素仅与 bitmap 具有相应 1 位才可见。若区域包括像素超出 rect 为 Widget,在该区域中的窗口系统控件可能是可见的,也可能是不可见的,这取决于平台。

注意:此效果可能很慢,若区域特别复杂。

以下代码展示如何使用具有 Alpha 通道的图像,去生成用于 Widget 的遮罩:

    QLabel topLevelLabel;
    QPixmap pixmap(":/images/tux.png");
    topLevelLabel.setPixmap(pixmap);
    topLevelLabel.setMask(pixmap.mask());
							

由此代码展示的标签使用它所包含的图像进行遮罩,让外观是不规则形状的图像被直接绘制到屏幕上。

被遮罩 Widget 仅在其可见部分,接收鼠标事件。

另请参阅 mask (), clearMask (), windowOpacity (),和 异形时钟范例 .

void QWidget:: setMask (const QRegion & region )

这是重载函数。

促使 Widget 部分仅重叠 region 才可见。若区域包括像素超出 rect 为 Widget,在该区域中的窗口系统控件可能是可见的,也可能是不可见的,这取决于平台。

注意:此效果可能很慢,若区域特别复杂。

另请参阅 windowOpacity .

void QWidget:: setMaximumSize ( int maxw , int maxh )

这是重载函数。

This function corresponds to setMaximumSize ( QSize ( maxw , maxh )). Sets the maximum width to maxw and the maximum height to maxh .

注意: Setter 函数为特性 maximumSize .

void QWidget:: setMinimumSize ( int minw , int minh )

这是重载函数。

This function corresponds to setMinimumSize ( QSize (minw, minh)). Sets the minimum width to minw and the minimum height to minh .

注意: Setter 函数为特性 minimumSize .

void QWidget:: setParent ( QWidget * parent )

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.

注意: 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.

警告: 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 .

另请参阅 setWindowFlags ().

void QWidget:: setParent ( QWidget * parent , Qt::WindowFlags f )

这是重载函数。

This function also takes widget flags, f 作为自变量。

void QWidget:: setShortcutAutoRepeat ( int id , bool enable = true)

enable is true, auto repeat of the shortcut with the given id is enabled; otherwise it is disabled.

This function was introduced in Qt 4.2.

另请参阅 grabShortcut () 和 releaseShortcut ().

void QWidget:: setShortcutEnabled ( int id , bool enable = true)

enable is true, the shortcut with the given id is enabled; otherwise the shortcut is disabled.

警告: You should not normally need to use this function since Qt's shortcut system enables/disables shortcuts automatically as widgets become hidden/visible and gain or lose focus. It is best to use QAction or QShortcut to handle shortcuts, since they are easier to use than this low-level function.

另请参阅 grabShortcut () 和 releaseShortcut ().

void QWidget:: setSizeIncrement ( int w , int h )

这是重载函数。

Sets the x (width) size increment to w and the y (height) size increment to h .

注意: Setter 函数为特性 sizeIncrement .

void QWidget:: setSizePolicy ( QSizePolicy::Policy horizontal , QSizePolicy::Policy vertical )

这是重载函数。

Sets the size policy of the widget to horizontal and vertical , with standard stretch and no height-for-width.

注意: Setter 函数为特性 sizePolicy .

另请参阅 QSizePolicy::QSizePolicy ().

void QWidget:: setStyle ( QStyle * style )

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 () 代替。

Setting a widget's style has no effect on existing or future child widgets.

警告: 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 style sheets are currently not supported for custom QStyle subclasses. We plan to address this in some future release.

另请参阅 style (), QStyle , QApplication::style (),和 QApplication::setStyle ().

[static] void QWidget:: setTabOrder ( QWidget * first , QWidget * second )

Puts the second widget after the first widget in the focus order.

It effectively removes the second widget from its focus chain and inserts it after the first 小部件。

Note that since the tab order of the second widget is changed, you should order a chain like this:

setTabOrder(a, b); // a to b
setTabOrder(b, c); // a to b to c
setTabOrder(c, d); // a to b to c to d
							

not like this:

// WRONG
setTabOrder(c, d); // c to d
setTabOrder(a, b); // a to b AND c to d
setTabOrder(b, c); // a to b to c, but not c to d
							

first or second has a focus proxy, setTabOrder() correctly substitutes the proxy.

注意: Since Qt 5.10: A widget that has a child as focus proxy is understood as a compound widget. When setting a tab order between one or two compound widgets, the local tab order inside each will be preserved. This means that if both widgets are compound widgets, the resulting tab order will be from the last child inside first , to the first child inside second .

另请参阅 setFocusPolicy (), setFocusProxy (),和 Widget 中的键盘焦点 .

void QWidget:: setWindowFlag ( Qt::WindowType flag , bool on = true)

Sets the window flag flag 在此 Widget 若 on is true; otherwise clears the flag.

This function was introduced in Qt 5.9.

另请参阅 setWindowFlags (), windowFlags (),和 windowType ().

void QWidget:: setWindowRole (const QString & role )

Sets the window's role to role . This only makes sense for windows on X11.

另请参阅 windowRole ().

void QWidget:: setWindowState ( Qt::WindowStates windowState )

Sets the window state to windowState . The window state is a OR'ed combination of Qt::WindowState : Qt::WindowMinimized , Qt::WindowMaximized , Qt::WindowFullScreen ,和 Qt::WindowActive .

If the window is not visible (i.e. isVisible () 返回 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.

注意: 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 .

另请参阅 Qt::WindowState and windowState ().

void QWidget:: setupUi ( QWidget * widget )

Sets up the user interface for the specified widget .

注意: This function is available with widgets that derive from user interface descriptions created using uic .

另请参阅 Using a Designer UI File in Your Application .

[slot] void QWidget:: show ()

展示 Widget 及其子级 Widget。

这相当于调用 showFullScreen (), showMaximized (),或 setVisible (true), depending on the platform's default behavior for the window flags.

另请参阅 raise (), showEvent (), hide (), setVisible (), showMinimized (), showMaximized (), showNormal (), isVisible (),和 windowFlags ().

[virtual protected] void QWidget:: showEvent ( QShowEvent * event )

此事件处理程序可在子类中被重实现,以接收 Widget 传入展示事件在 event 参数。

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 ().

另请参阅 visible , event (),和 QShowEvent .

[slot] void QWidget:: showFullScreen ()

以全屏模式展示 Widget。

调用此函数仅影响 windows .

要从全屏模式返回,调用 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.

另请参阅 showNormal (), showMaximized (), show (), hide (),和 isVisible ().

[slot] void QWidget:: showMaximized ()

最大化展示 Widget。

调用此函数仅影响 windows .

On X11, this function may not work properly with certain window managers. See the 窗口几何体 documentation for an explanation.

另请参阅 setWindowState (), showNormal (), showMinimized (), show (), hide (),和 isVisible ().

[slot] void QWidget:: showMinimized ()

以图标形式最小化展示 Widget。

调用此函数仅影响 windows .

另请参阅 showNormal (), showMaximized (), show (), hide (), isVisible (),和 isMinimized ().

[slot] void QWidget:: showNormal ()

还原 Widget 在它被最大化或最小化之后。

调用此函数仅影响 windows .

另请参阅 setWindowState (), showMinimized (), showMaximized (), show (), hide (),和 isVisible ().

void QWidget:: stackUnder ( QWidget * w )

下置 Widget w 在父级 Widget 的堆栈。

要使这工作,Widget 本身和 w 必须同级。

另请参阅 raise () 和 lower ().

QStyle *QWidget:: style () const

另请参阅 QWidget::setStyle (), QApplication::setStyle (),和 QApplication::style ().

[virtual protected] void QWidget:: tabletEvent ( QTabletEvent * event )

此事件处理程序对于事件 event ,可在子类中重新实现以接收 Widget 的 Tablet (平板电脑) 事件。

若重实现此处理程序,非常重要的是 ignore() 事件若不处理它,以便 Widget 父级可以解释它。

默认实现忽略事件。

If tablet tracking is switched off, tablet move events only occur if the stylus is in contact with the tablet, or at least one stylus button is pressed, while the stylus is being moved. If tablet tracking is switched on, tablet move events occur even while the stylus is hovering in proximity of the tablet, with no buttons pressed.

另请参阅 QEvent::ignore (), QEvent::accept (), event (), setTabletTracking (),和 QTabletEvent .

bool QWidget:: testAttribute ( Qt::WidgetAttribute attribute ) const

返回 true 若属性 attribute 在此 Widget 被设置;否则返回 false .

另请参阅 setAttribute ().

bool QWidget:: underMouse () const

返回 true 若 Widget 在鼠标光标下方;否则返回 false .

此值不会正确更新,在拖放操作期间。

另请参阅 enterEvent () 和 leaveEvent ().

void QWidget:: ungrabGesture ( Qt::GestureType gesture )

退订 Widget 从给定 gesture type

This function was introduced in Qt 4.6.

另请参阅 grabGesture () 和 QGestureEvent .

[slot] void QWidget:: update ()

更新 Widget 除非更新被禁用或 Widget 被隐藏。

此函数不会导致立即重新绘制;相反,它在 Qt 返回到主事件循环时调度描绘处理事件。这准许 Qt 去优化以提高速度并减少闪烁相比调用 repaint () 做。

多次调用 update() 通常仅仅导致一次 paintEvent () 调用。

Qt 通常先擦除 Widget 区域再 paintEvent () 调用。若 Qt::WA_OpaquePaintEvent Widget 属性被设置,Widget 负责采用不透明颜色描绘其所有像素。

另请参阅 repaint (), paintEvent (), setUpdatesEnabled (),和 指针式时钟范例 .

void QWidget:: update ( int x , int y , int w , int h )

这是重载函数。

此版本更新矩形 ( x , y , w , h ) 在 Widget 内。

void QWidget:: update (const QRect & rect )

这是重载函数。

此版本更新矩形 rect 在 Widget 内。

void QWidget:: update (const QRegion & rgn )

这是重载函数。

此版本重新描绘区域 rgn 在 Widget 内。

void QWidget:: updateGeometry ()

通知布局系统此 Widget 已改变,且可能需要更改几何体。

调用此函数,若 sizeHint () 或 sizePolicy () 已改变。

对于明确隐藏 Widget,updateGeometry() 是空操作。会尽快通知布局系统,Widget 一展示。

[protected slot] void QWidget:: updateMicroFocus ()

更新 Widget 的微聚焦。

QRegion QWidget:: visibleRegion () const

返回可以发生描绘事件的未遮盖区域。

对于可见 Widget,这是其它 Widget 未覆盖的近似区域;否则,这是空区域。

repaint () 函数会调用此函数若有必要,因此通常不需要调用它。

[virtual protected] void QWidget:: wheelEvent ( QWheelEvent * event )

此事件处理程序对于事件 event ,可以在子类中被重实现以接收 Widget 滚轮事件。

若重实现此处理程序,非常重要的是 ignore() 事件若不处理它,以便 Widget 父级可以解释它。

默认实现忽略事件。

另请参阅 QEvent::ignore (), QEvent::accept (), event (),和 QWheelEvent .

WId QWidget:: winId () const

返回 Widget 的窗口系统标识符。

原则上是可移植的,但若使用它,可能会做一些不可移植的事情。小心。

若 Widget 非本机 (外来) 且在其上援引了 winId(),则该 Widget 会提供本机句柄。

This value may change at run-time. An event with type QEvent::WinIdChange will be sent to the widget following a change in window system identifier.

另请参阅 find ().

QWidget *QWidget:: window () const

返回用于此 Widget 的窗口,即具有 (或可能具有) 窗口系统框架的下一祖先 Widget。

若 Widget 是窗口,Widget 本身被返回。

典型用法是更改窗口标题:

aWidget->window()->setWindowTitle("New Window Title");
							

另请参阅 isWindow ().

QWindow *QWidget:: windowHandle () const

如果这是本机 Widget,返回关联 QWindow 。否则返回 null。

Native widgets include toplevel widgets, QGLWidget, and child widgets on which winId () 被调用。

This function was introduced in Qt 5.0.

另请参阅 winId ().

[signal] void QWidget:: windowIconChanged (const QIcon & icon )

此信号被发射当窗口图标已改变,采用新的 icon 作为自变量。

This function was introduced in Qt 5.2.

注意: 通知信号为特性 windowIcon .

QString QWidget:: windowRole () const

返回窗口的角色 (或空字符串)。

另请参阅 setWindowRole (), windowIcon ,和 windowTitle .

Qt::WindowStates QWidget:: windowState () const

返回当前窗口状态。窗口状态是或组合的 Qt::WindowState : Qt::WindowMinimized , Qt::WindowMaximized , Qt::WindowFullScreen ,和 Qt::WindowActive .

另请参阅 Qt::WindowState and setWindowState ().

[signal] void QWidget:: windowTitleChanged (const QString & title )

此信号被发射当窗口标题已改变,采用新的 title 作为自变量。

This function was introduced in Qt 5.2.

注意: 通知信号为特性 windowTitle .

Qt::WindowType QWidget:: windowType () const

返回此 Widget 的窗口类型。这等同于 windowFlags () & Qt::WindowType_Mask .

另请参阅 windowFlags .

宏文档编制

QWIDGETSIZE_MAX

定义最大尺寸,为 QWidget 对象。

Widget 的最大允许尺寸为 QSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).

另请参阅 QWidget::setMaximumSize ().