Qt No Such Slot Qwidget

The QApplication class manages the GUI application's control flow and main settings. More...

Header:#include <QApplication>
qmake: QT += widgets
Inherits:QGuiApplication

Properties

  • autoSipEnabled : bool
  • cursorFlashTime : int
  • doubleClickInterval : int
  • globalStrut : QSize
  • keyboardInputInterval : int
  • startDragDistance : int
  • startDragTime : int
  • styleSheet : QString
  • wheelScrollLines : int
  • windowIcon : QIcon

Qt no such slot qapplication You are not going to experience much qt no such slot qapplication excitement if you bet too much and squander all of your bankroll in the 1st few mins.There are a variety of other betting options in the game of Craps. 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.

  • 7 properties inherited from QGuiApplication
  • 5 properties inherited from QCoreApplication
  • 1 property inherited from QObject

Public Functions

QApplication(int &argc, char **argv)
virtual ~QApplication()
QString styleSheet() const

Reimplemented Public Functions

virtual bool notify(QObject *receiver, QEvent *e)
  • 6 public functions inherited from QGuiApplication
  • 3 public functions inherited from QCoreApplication
  • 32 public functions inherited from QObject

Public Slots

void aboutQt()
bool autoSipEnabled() const
void closeAllWindows()
void setAutoSipEnabled(const bool enabled)
void setStyleSheet(const QString &sheet)
  • 1 public slot inherited from QCoreApplication
  • 1 public slot inherited from QObject

Signals

  • 13 signals inherited from QGuiApplication
  • 1 signal inherited from QCoreApplication
  • 2 signals inherited from QObject

Static Public Members

QWidget *activeModalWidget()
QWidget *activePopupWidget()
QWidget *activeWindow()
void alert(QWidget *widget, int msec = 0)
QWidgetList allWidgets()
void beep()
int cursorFlashTime()
QDesktopWidget *desktop()
int doubleClickInterval()
int exec()
QWidget *focusWidget()
QFont font()
QFont font(const QWidget *widget)
QFont font(const char *className)
QFontMetrics fontMetrics()
QSize globalStrut()
bool isEffectEnabled(Qt::UIEffect effect)
int keyboardInputInterval()
Qt::NavigationMode navigationMode()
QPalette palette(const QWidget *widget)
QPalette palette(const char *className)
void setActiveWindow(QWidget *active)
void setCursorFlashTime(int)
void setDoubleClickInterval(int)
void setEffectEnabled(Qt::UIEffect effect, bool enable = true)
void setFont(const QFont &font, const char *className = Q_NULLPTR)
void setGlobalStrut(const QSize &)
void setKeyboardInputInterval(int)
void setNavigationMode(Qt::NavigationMode mode)
void setPalette(const QPalette &palette, const char *className = Q_NULLPTR)
void setStartDragDistance(int l)
void setStartDragTime(int ms)
void setStyle(QStyle *style)
QStyle *setStyle(const QString &style)
void setWheelScrollLines(int)
void setWindowIcon(const QIcon &icon)
int startDragDistance()
int startDragTime()
QStyle *style()
QWidget *topLevelAt(const QPoint &point)
QWidget *topLevelAt(int x, int y)
QWidgetList topLevelWidgets()
int wheelScrollLines()
QWidget *widgetAt(const QPoint &point)
QWidget *widgetAt(int x, int y)
QIcon windowIcon()
  • 44 static public members inherited from QGuiApplication
  • 38 static public members inherited from QCoreApplication
  • 11 static public members inherited from QObject

Reimplemented Protected Functions

  • 1 protected function inherited from QGuiApplication
  • 1 protected function inherited from QCoreApplication
  • 9 protected functions inherited from QObject

Macros

qApp

Detailed Description

The QApplication class manages the GUI application's control flow and main settings.

QApplication specializes QGuiApplication with some functionality needed for QWidget-based applications. It handles widget specific initialization, finalization.

For any GUI application using Qt, there is precisely oneQApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time. For non-QWidget based Qt applications, use QGuiApplication instead, as it does not depend on the QtWidgets library.

Some GUI applications provide a special batch mode ie. provide command line arguments for executing tasks without manual intervention. In such non-GUI mode, it is often sufficient to instantiate a plain QCoreApplication to avoid unnecessarily initializing resources needed for a graphical user interface. The following example shows how to dynamically create an appropriate type of application instance:

The QApplication object is accessible through the instance() function that returns a pointer equivalent to the global qApp pointer.

QApplication's main areas of responsibility are:

  • It initializes the application with the user's desktop settings such as palette(), font() and doubleClickInterval(). It keeps track of these properties in case the user changes the desktop globally, for example through some kind of control panel.
  • It performs event handling, meaning that it receives events from the underlying window system and dispatches them to the relevant widgets. By using sendEvent() and postEvent() you can send your own events to widgets.
  • It parses common command line arguments and sets its internal state accordingly. See the constructor documentation below for more details.
  • It defines the application's look and feel, which is encapsulated in a QStyle object. This can be changed at runtime with setStyle().
  • It specifies how the application is to allocate colors. See setColorSpec() for details.
  • It provides localization of strings that are visible to the user via translate().
  • It provides some magical objects like the desktop() and the clipboard().
  • It knows about the application's windows. You can ask which widget is at a certain position using widgetAt(), get a list of topLevelWidgets() and closeAllWindows(), etc.
  • It manages the application's mouse cursor handling, see setOverrideCursor()

Since the QApplication object does so much initialization, it must be created before any other objects related to the user interface are created. QApplication also deals with common command line arguments. Hence, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself.

Groups of functions
System settingsdesktopSettingsAware(), setDesktopSettingsAware(), cursorFlashTime(), setCursorFlashTime(), doubleClickInterval(), setDoubleClickInterval(), setKeyboardInputInterval(), wheelScrollLines(), setWheelScrollLines(), palette(), setPalette(), font(), setFont(), fontMetrics().
Event handlingexec(), processEvents(), exit(), quit(). sendEvent(), postEvent(), sendPostedEvents(), removePostedEvents(), hasPendingEvents(), notify().
GUI Stylesstyle(), setStyle().
Color usagecolorSpec(), setColorSpec().
Text handlinginstallTranslator(), removeTranslator() translate().
WidgetsallWidgets(), topLevelWidgets(), desktop(), activePopupWidget(), activeModalWidget(), clipboard(), focusWidget(), activeWindow(), widgetAt().
Advanced cursor handlingoverrideCursor(), setOverrideCursor(), restoreOverrideCursor().
MiscellaneouscloseAllWindows(), startingUp(), closingDown().

See also QCoreApplication, QAbstractEventDispatcher, QEventLoop, and QSettings.

Property Documentation

autoSipEnabled : bool

toggles automatic SIP (software input panel) visibility

Set this property to true to automatically display the SIP when entering widgets that accept keyboard input. This property only affects widgets with the WA_InputMethodEnabled attribute set, and is typically used to launch a virtual keyboard on devices which have very few or no keys.

The property only has an effect on platforms that use software input panels.

The default is platform dependent.

This property was introduced in Qt 4.5.

Access functions:

bool autoSipEnabled() const
void setAutoSipEnabled(const bool enabled)

cursorFlashTime : int

This property holds the text cursor's flash (blink) time in milliseconds

The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for half the cursor flash time, then hidden for the same amount of time, but this may vary.

The default value on X11 is 1000 milliseconds. On Windows, the Control Panel value is used and setting this property sets the cursor flash time for all applications.

We recommend that widgets do not cache this value as it may change at any time if the user changes the global desktop settings.

Note: This property may hold a negative value, for instance if cursor blinking is disabled.

Access functions:

int cursorFlashTime()
void setCursorFlashTime(int)

doubleClickInterval : int

This property holds the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks

The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system's value is used.

Access functions:

int doubleClickInterval()
void setDoubleClickInterval(int)

globalStrut : QSize

This property holds the minimum size that any GUI element that the user can interact with should have

For example, no button should be resized to be smaller than the global strut size. The strut size should be considered when reimplementing GUI controls that may be used on touch-screens or similar I/O devices.

Example:

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

Access functions:

QSize globalStrut()
void setGlobalStrut(const QSize &)

keyboardInputInterval : int

This property holds the time limit in milliseconds that distinguishes a key press from two consecutive key presses

The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system's value is used.

This property was introduced in Qt 4.2.

Access functions:

int keyboardInputInterval()
void setKeyboardInputInterval(int)

startDragDistance : int

If you support drag and drop in your application, and want to start a drag and drop operation after the user has moved the cursor a certain distance with a button held down, you should use this property's value as the minimum distance required.

For example, if the mouse position of the click is stored in startPos and the current position (e.g. in the mouse move event) is currentPos, you can find out if a drag should be started with code like this:

Qt uses this value internally, e.g. in QFileDialog.

The default value (if the platform doesn't provide a different default) is 10 pixels.

Access functions:

int startDragDistance()
void setStartDragDistance(int l)

See also startDragTime(), QPoint::manhattanLength(), and Drag and Drop.

startDragTime : int

This property holds the time in milliseconds that a mouse button must be held down before a drag and drop operation will begin

If you support drag and drop in your application, and want to start a drag and drop operation after the user has held down a mouse button for a certain amount of time, you should use this property's value as the delay.

Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for starting a drag.

The default value is 500 ms.

Access functions:

int startDragTime()
void setStartDragTime(int ms)

See also startDragDistance() and Drag and Drop.

styleSheet : QString

This property holds the application style sheet

By default, this property returns an empty string unless the user specifies the -stylesheet option on the command line when running the application.

This property was introduced in Qt 4.2.

Access functions:

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

See also QWidget::setStyle() and Qt Style Sheets.

wheelScrollLines : int

This property holds the number of lines to scroll a widget, when the mouse wheel is rotated.

If the value exceeds the widget's number of visible lines, the widget should interpret the scroll operation as a single page up or page down. If the widget is an item view class, then the result of scrolling one line depends on the setting of the widget's scroll mode. Scroll one line can mean scroll one item or scroll one pixel.

By default, this property has a value of 3.

Access functions:

int wheelScrollLines()
void setWheelScrollLines(int)

See also QStyleHints::wheelScrollLines().

windowIcon : QIcon

This property holds the default window icon

Access functions:

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

See also QWidget::setWindowIcon() and Setting the Application Icon.

Member Function Documentation

QApplication::QApplication(int &argc, char **argv)

Initializes the window system and constructs an application object with argc command line arguments in argv.

Warning: The data referred to by argc and argv must stay valid for the entire lifetime of the QApplication object. In addition, argc must be greater than zero and argv must contain at least one valid character string.

The global qApp pointer refers to this application object. Only one application object should be created.

This application object must be constructed before any paint devices (including widgets, pixmaps, bitmaps etc.).

Note: argc and argv might be changed as Qt removes command line arguments that it recognizes.

All Qt programs automatically support the following command line options:

  • -style= style, sets the application GUI style. Possible values depend on your system configuration. If you compiled Qt with additional styles or have additional styles as plugins these will be available to the -style command line option. You can also set the style for all Qt applications by setting the QT_STYLE_OVERRIDE environment variable.
  • -style style, is the same as listed above.
  • -stylesheet= stylesheet, sets the application styleSheet. The value must be a path to a file that contains the Style Sheet.

    Note: Relative URLs in the Style Sheet file are relative to the Style Sheet file's path.

  • -stylesheet stylesheet, is the same as listed above.
  • -widgetcount, prints debug message at the end about number of widgets left undestroyed and maximum number of widgets existed at the same time
  • -reverse, sets the application's layout direction to Qt::RightToLeft
  • -qmljsdebugger=, activates the QML/JS debugger with a specified port. The value must be of format port:1234[,block], where block is optional and will make the application wait until a debugger connects to it.

See also QCoreApplication::arguments().

[virtual] QApplication::~QApplication()

Cleans up any window system resources that were allocated by this application. Sets the global variable qApp to 0.

[static slot] void QApplication::aboutQt()

Displays a simple message box about Qt. The message includes the version number of Qt being used by the application.

This is useful for inclusion in the Help menu of an application, as shown in the Menus example.

This function is a convenience slot for QMessageBox::aboutQt().

[static] QWidget *QApplication::activeModalWidget()

Returns the active modal widget.

A modal widget is a special top-level widget which is a subclass of QDialog that specifies the modal parameter of the constructor as true. A modal widget must be closed before the user can continue with other parts of the program.

Modal widgets are organized in a stack. This function returns the active modal widget at the top of the stack.

See also activePopupWidget() and topLevelWidgets().

[static] QWidget *QApplication::activePopupWidget()

Returns the active popup widget.

A popup widget is a special top-level widget that sets the Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application opens a popup widget, all events are sent to the popup. Normal widgets and modal widgets cannot be accessed before the popup widget is closed.

Only other popup widgets may be opened when a popup widget is shown. The popup widgets are organized in a stack. This function returns the active popup widget at the top of the stack.

See also activeModalWidget() and topLevelWidgets().

[static] QWidget *QApplication::activeWindow()

Returns the application top-level window that has the keyboard input focus, or 0 if no application window has the focus. There might be an activeWindow() even if there is no focusWidget(), for example if no widget in that window accepts key events.

See also setActiveWindow(), QWidget::setFocus(), QWidget::hasFocus(), and focusWidget().

[static] void QApplication::alert(QWidget *widget, intmsec = 0)

Causes an alert to be shown for widget if the window is not the active window. The alert is shown for msec miliseconds. If msec is zero (the default), then the alert is shown indefinitely until the window becomes active again.

Currently this function does nothing on Qt for Embedded Linux.

On macOS, this works more at the application level and will cause the application icon to bounce in the dock.

On Windows, this causes the window's taskbar entry to flash for a time. If msec is zero, the flashing will stop and the taskbar entry will turn a different color (currently orange).

On X11, this will cause the window to be marked as 'demands attention', the window must not be hidden (i.e. not have hide() called on it, but be visible in some sort of way) in order for this to work.

This function was introduced in Qt 4.3.

[static] QWidgetList QApplication::allWidgets()

Returns a list of all the widgets in the application.

The list is empty (QList::isEmpty()) if there are no widgets.

Note: Some of the widgets may be hidden.

Example:

See also topLevelWidgets() and QWidget::isVisible().

[static] void QApplication::beep()

Sounds the bell, using the default volume and sound. The function is not available in Qt for Embedded Linux.

[static slot] void QApplication::closeAllWindows()

Closes all top-level windows.

This function is particularly useful for applications with many top-level windows. It could, for example, be connected to a Exit entry in the File menu:

Slots

The windows are closed in random order, until one window does not accept the close event. The application quits when the last window was successfully closed; this can be turned off by setting quitOnLastWindowClosed to false.

See also quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(), QWidget::closeEvent(), lastWindowClosed(), QCoreApplication::quit(), topLevelWidgets(), and QWidget::isWindow().

[static] QDesktopWidget *QApplication::desktop()

Returns the desktop widget (also called the root window).

The desktop may be composed of multiple screens, so it would be incorrect, for example, to attempt to center some widget in the desktop's geometry. QDesktopWidget has various functions for obtaining useful geometries upon the desktop, such as QDesktopWidget::screenGeometry() and QDesktopWidget::availableGeometry().

On X11, it is also possible to draw on the desktop.

[virtual protected] bool QApplication::event(QEvent *e)

Reimplemented from QObject::event().

[static] int QApplication::exec()

Enters the main event loop and waits until exit() is called, then returns the value that was set to exit() (which is 0 if exit() is called via quit()).

It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets.

Generally, no user interaction can take place before calling exec(). As a special case, modal widgets like QMessageBox can be used before calling exec(), because modal widgets call exec() to start a local event loop.

To make your application perform idle processing, i.e., executing a special function whenever there are no pending events, use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function. This is because, on some platforms the QApplication::exec() call may not return. For example, on the Windows platform, when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function, after the QApplication::exec() call.

See also quitOnLastWindowClosed, QCoreApplication::quit(), QCoreApplication::exit(), QCoreApplication::processEvents(), and QCoreApplication::exec().

[signal] void QApplication::focusChanged(QWidget *old, QWidget *now)

This signal is emitted when the widget that has keyboard focus changed from old to now, i.e., because the user pressed the tab-key, clicked into a widget or changed the active window. Both old and now can be the null-pointer.

The signal is emitted after both widget have been notified about the change through QFocusEvent.

This function was introduced in Qt 4.1.

See also QWidget::setFocus(), QWidget::clearFocus(), and Qt::FocusReason.

[static] QWidget *QApplication::focusWidget()

Returns the application widget that has the keyboard input focus, or 0 if no widget in this application has the focus.

See also QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), and focusChanged().

[static] QFont QApplication::font()

Returns the default application font.

See also setFont(), fontMetrics(), and QWidget::font().

[static] QFont QApplication::font(const QWidget *widget)

This is an overloaded function.

Returns the default font for the widget.

See also fontMetrics() and QWidget::setFont().

[static] QFont QApplication::font(const char *className)

This is an overloaded function.

Returns the font for widgets of the given className.

See also setFont() and QWidget::font().

[static] QFontMetrics QApplication::fontMetrics()

Returns display (screen) font metrics for the application font.

See also font(), setFont(), QWidget::fontMetrics(), and QPainter::fontMetrics().

[static] bool QApplication::isEffectEnabled(Qt::UIEffecteffect)

Returns true if effect is enabled; otherwise returns false.

By default, Qt will try to use the desktop settings. To prevent this, call setDesktopSettingsAware(false).

Note: All effects are disabled on screens running at less than 16-bit color depth.

See also setEffectEnabled() and Qt::UIEffect.

[static] Qt::NavigationMode QApplication::navigationMode()

Returns what kind of focus navigation Qt is using.

This feature is available in Qt for Embedded Linux only.

This function was introduced in Qt 4.6.

See also setNavigationMode() and keypadNavigationEnabled().

[virtual] bool QApplication::notify(QObject *receiver, QEvent *e)

Reimplemented from QCoreApplication::notify().

[static] QPalette QApplication::palette(const QWidget *widget)

This is an overloaded function.

If a widget is passed, the default palette for the widget's class is returned. This may or may not be the application palette. In most cases there is no special palette for certain types of widgets, but one notable exception is the popup menu under Windows, if the user has defined a special background color for menus in the display settings.

See also setPalette() and QWidget::palette().

[static] QPalette QApplication::palette(const char *className)

This is an overloaded function.

Returns the palette for widgets of the given className.

See also setPalette() and QWidget::palette().

[static] void QApplication::setActiveWindow(QWidget *active)

Sets the active window to the active widget in response to a system event. The function is called from the platform specific event handlers.

Warning: This function does not set the keyboard focus to the active widget. Call QWidget::activateWindow() instead.

It sets the activeWindow() and focusWidget() attributes and sends proper WindowActivate/WindowDeactivate and FocusIn/FocusOut events to all appropriate widgets. The window will then be painted in active state (e.g. cursors in line edits will blink), and it will have tool tips enabled.

Pointer To Qwidget In Signals And Slots

See also activeWindow() and QWidget::activateWindow().

[static] void QApplication::setEffectEnabled(Qt::UIEffecteffect, boolenable = true)

Enables the UI effect effect if enable is true, otherwise the effect will not be used.

Note: All effects are disabled on screens running at less than 16-bit color depth.

See also isEffectEnabled(), Qt::UIEffect, and setDesktopSettingsAware().

[static] void QApplication::setFont(const QFont &font, const char *className = Q_NULLPTR)

Changes the default application font to font. If className is passed, the change applies only to classes that inherit className (as reported by QObject::inherits()).

On application start-up, the default font depends on the window system. It can vary depending on both the window system version and the locale. This function lets you override the default font; but overriding may be a bad idea because, for example, some locales need extra large fonts to support their special characters.

Qt No Such Slot Qwidget

Warning: Do not use this function in conjunction with Qt Style Sheets. The font of an application can be customized using the 'font' style sheet property. To set a bold font for all QPushButtons, set the application styleSheet() as 'QPushButton { font: bold }'

See also font(), fontMetrics(), and QWidget::setFont().

[static] void QApplication::setNavigationMode(Qt::NavigationModemode)

Sets the kind of focus navigation Qt should use to mode.

This feature is available in Qt for Embedded Linux only.

This function was introduced in Qt 4.6.

See also navigationMode() and keypadNavigationEnabled().

[static] void QApplication::setPalette(const QPalette &palette, const char *className = Q_NULLPTR)

Changes the default application palette to palette.

If className is passed, the change applies only to widgets that inherit className (as reported by QObject::inherits()). If className is left 0, the change affects all widgets, thus overriding any previously set class specific palettes.

The palette may be changed according to the current GUI style in QStyle::polish().

Warning: Do not use this function in conjunction with Qt Style Sheets. 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'.

Note: Some styles do not use the palette for all drawing, for instance, if they make use of native theme engines. This is the case for the Windows XP, Windows Vista, and macOS styles.

See also QWidget::setPalette(), palette(), and QStyle::polish().

[static] void QApplication::setStyle(QStyle *style)

Sets the application's GUI style to style. Ownership of the style object is transferred to QApplication, so QApplication will delete the style object on application exit or when a new style is set and the old style is still the parent of the application object.

Example usage:

When switching application styles, the color palette is set back to the initial colors or the system defaults. This is necessary since certain styles have to adapt the color palette to be fully style-guide compliant.

Setting the style before a palette has been set, i.e., before creating QApplication, will cause the application to use QStyle::standardPalette() for the palette.

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

See also style(), QStyle, setPalette(), and desktopSettingsAware().

[static] QStyle *QApplication::setStyle(const QString &style)

This is an overloaded function.

Requests a QStyle object for style from the QStyleFactory.

The string must be one of the QStyleFactory::keys(), typically one of 'windows', 'fusion', 'windowsxp', or 'macintosh'. Style names are case insensitive.

Returns 0 if an unknown style is passed, otherwise the QStyle object returned is set as the application's GUI style.

Warning: To ensure that the application's style is set correctly, it is best to call this function before the QApplication constructor, if possible.

[static] QStyle *QApplication::style()

Returns the application's style object.

See also setStyle() and QStyle.

[static] QWidget *QApplication::topLevelAt(const QPoint &point)

Returns the top-level widget at the given point; returns 0 if there is no such widget.

[static] QWidget *QApplication::topLevelAt(intx, inty)

This is an overloaded function.

Returns the top-level widget at the point (x, y); returns 0 if there is no such widget.

[static] QWidgetList QApplication::topLevelWidgets()

Returns a list of the top-level widgets (windows) in the application.

Note: Some of the top-level widgets may be hidden, for example a tooltip if no tooltip is currently shown.

Example:

See also allWidgets(), QWidget::isWindow(), and QWidget::isHidden().

[static] QWidget *QApplication::widgetAt(const QPoint &point)

Returns the widget at global screen position point, or 0 if there is no Qt widget there.

This function can be slow.

See also QCursor::pos(), QWidget::grabMouse(), and QWidget::grabKeyboard().

[static] QWidget *QApplication::widgetAt(intx, inty)

This is an overloaded function.

Returns the widget at global screen position (x, y), or 0 if there is no Qt widget there.

Macro Documentation

qApp

A global pointer referring to the unique application object. It is equivalent to QCoreApplication::instance(), but cast as a QApplication pointer, so only valid when the unique application object is a QApplication.

See also QCoreApplication::instance() and qGuiApp.

© 2019 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Home > Articles > Programming > C/C++

  1. Subclassing QWidget
< BackPage 2 of 4Next >
This chapter is from the book
C++ GUI Programming with Qt4, 2nd Edition

This chapter is from the book

This chapter is from the book

Subclassing QWidget

Many custom widgets are simply a combination of existing widgets, whether they are built-in Qt widgets or other custom widgets such as HexSpinBox. Custom widgets that are built by composing existing widgets can usually be developed in Qt Designer:

  1. Create a new form using the 'Widget' template.
  2. Add the necessary widgets to the form, and lay them out.
  3. Set up the signals and slots connections.
  4. If behavior beyond what can be achieved through signals and slots is required, write the necessary code in a class that is derived from both QWidget and the uic-generated class.

Naturally, combining existing widgets can also be done entirely in code. Whichever approach is taken, the resulting class is a QWidget subclass.

If the widget has no signals and slots of its own and doesn't reimplement any virtual functions, it is even possible to simply assemble the widget by combining existing widgets without a subclass. That's the approach we used in Chapter 1 to create the Age application, with a QWidget, a QSpinBox, and a QSlider. Even so, we could just as easily have subclassed QWidget and created the QSpinBox and QSlider in the subclass's constructor.

When none of Qt's widgets are suitable for the task at hand, and when there is no way to combine or adapt existing widgets to obtain the desired result, we can still create the widget we want. This is achieved by subclassing QWidget and reimplementing a few event handlers to paint the widget and to respond to mouse clicks. This approach gives us complete freedom to define and control both the appearance and the behavior of our widget. Qt's built-in widgets, such as QLabel, QPushButton, and QTableWidget, are implemented this way. If they didn't exist in Qt, it would still be possible to create them ourselves using the public functions provided by QWidget in a completely platform-independent manner.

To demonstrate how to write a custom widget using this approach, we will create the IconEditor widget shown in Figure 5.2. The IconEditor is a widget that could be used in an icon editing program.

Figure 5.2 The widget

In practice, before diving in and creating a custom widget, it is always worth checking whether the widget is already available, either as a Qt Solution (http://www.trolltech.com/products/qt/addon/solutions/catalog/4/) or from a commercial or non-commercial third party (http://www.trolltech.com/products/qt/3rdparty/), since this could save a lot of time and effort. In this case, we will assume that no suitable widget is available, and so we will create our own.

Let's begin by reviewing the header file.

The IconEditor class uses the Q_PROPERTY() macro to declare three custom properties: penColor, iconImage, and zoomFactor. Each property has a data type, a 'read' function, and an optional 'write' function. For example, the penColor property is of type QColor and can be read and written using the penColor() and setPenColor() functions.

When we make use of the widget in Qt Designer, custom properties appear in Qt Designer's property editor below the properties inherited from QWidget. Properties may be of any type supported by QVariant. The Q_OBJECT macro is necessary for classes that define properties.

IconEditor reimplements three protected functions from QWidget and has a few private functions and variables. The three private variables hold the values of the three properties.

The implementation file begins with the IconEditor's constructor:

The constructor has some subtle aspects, such as the Qt::WA_StaticContents attribute and the setSizePolicy() call. We will discuss them shortly.

The pen color is set to black. The zoom factor is set to 8, meaning that each pixel in the icon will be rendered as an 8 x 8 square.

The icon data is stored in the image member variable and can be accessed through the setIconImage() and iconImage() functions. An icon editor program would typically call setIconImage() when the user opens an icon file and iconImage() to retrieve the icon when the user wants to save it. The image variable is of type QImage. We initialize it to 16 x 16 pixels and 32-bit ARGB format, a format that supports semi-transparency. We clear the image data by filling it with a transparent color.

The QImage class stores an image in a hardware-independent fashion. It can be set to use a 1-bit, 8-bit, or 32-bit depth. An image with 32-bit depth uses 8 bits for each of the red, green, and blue components of a pixel. The remaining 8 bits store the pixel's alpha component (opacity). For example, a pure red color's red, green, blue, and alpha components have the values 255, 0, 0, and 255. In Qt, this color can be specified as

or, since the color is opaque, as

QRgb is simply a typedef for unsigned int, and qRgb() and qRgba() are inline functions that combine their arguments into one 32-bit ARGB integer value. It is also possible to write

where the first FF corresponds to the alpha component and the second FF to the red component. In the IconEditor constructor, we fill the QImage with a transparent color by using 0 as the alpha component.

Qt provides two types for storing colors: QRgb and QColor. Whereas QRgb is only a typedef used in QImage to store 32-bit pixel data, QColor is a class with many useful functions and is widely used in Qt to store colors. In the IconEditor widget, we use QRgb only when dealing with the QImage; we use QColor for everything else, including the penColor property.

Qwidget Paintevent

The sizeHint() function is reimplemented from QWidget and returns the ideal size of a widget. Here, we take the image size multiplied by the zoom factor, with one extra pixel in each direction to accommodate a grid if the zoom factor is 3 or more. (We don't show a grid if the zoom factor is 2 or 1, because then the grid would leave hardly any room for the icon's pixels.)

A widget's size hint is mostly useful in conjunction with layouts. Qt's layout managers try as much as possible to respect a widget's size hint when they lay out a form's child widgets. For IconEditor to be a good layout citizen, it must report a credible size hint.

In addition to the size hint, widgets have a size policy that tells the layout system whether they like to be stretched and shrunk. By calling setSizePolicy() in the constructor with QSizePolicy::Minimum as horizontal and vertical policies, we tell any layout manager that is responsible for this widget that the widget's size hint is really its minimum size. In other words, the widget can be stretched if required, but it should never shrink below the size hint. This can be overridden in Qt Designer by setting the widget's sizePolicy property. We explain the meaning of the various size policies in Chapter 6.

The setPenColor() function sets the current pen color. The color will be used for newly drawn pixels.

The setIconImage() function sets the image to edit. We call convertToFormat() to make the image 32-bit with an alpha buffer, if it isn't already. Elsewhere in the code, we will assume that the image data is stored as 32-bit ARGB values.

After setting the image variable, we call QWidget::update() to schedule a repainting of the widget using the new image. Next, we call QWidget::updateGeometry() to tell any layout that contains the widget that the widget's size hint has changed. The layout will then automatically adapt to the new size hint.

The setZoomFactor() function sets the zoom factor for the image. To prevent division by zero elsewhere, we correct any value below 1. Again, we call update() and updateGeometry() to repaint the widget and to notify any managing layout about the size hint change.

The penColor(), iconImage(), and zoomFactor() functions are implemented as inline functions in the header file.

We will now review the code for the paintEvent() function. This function is IconEditor's most important function. It is called whenever the widget needs repainting. The default implementation in QWidget does nothing, leaving the widget blank.

Just like closeEvent(), which we met in Chapter 3, paintEvent() is an event handler. Qt has many other event handlers, each of which corresponds to a different type of event. Chapter 7 covers event processing in depth.

There are many situations when a paint event is generated and paintEvent() is called. For example:

  • When a widget is shown for the first time, the system automatically generates a paint event to force the widget to paint itself.
  • When a widget is resized, the system generates a paint event.
  • If the widget is obscured by another window and then revealed again, a paint event is generated for the area that was hidden (unless the window system stored the area).

We can also force a paint event by calling QWidget::update() or QWidget::repaint(). The difference between these two functions is that repaint() forces an immediate repaint, whereas update() simply schedules a paint event for when Qt next processes events. (Both functions do nothing if the widget isn't visible on-screen.) If update() is called multiple times, Qt compresses the consecutive paint events into a single paint event to avoid flicker. In IconEditor, we always use update().

Here's the code:

We start by constructing a QPainter object on the widget. If the zoom factor is 3 or more, we draw the horizontal and vertical lines that form the grid using the QPainter::drawLine() function.

A call to QPainter::drawLine() has the following syntax:

where (x1, y1) is the position of one end of the line and (x2, y2) is the position of the other end. There is also an overloaded version of the function that takes two QPoints instead of four ints.

The top-left pixel of a Qt widget is located at position (0, 0), and the bottom-right pixel is located at (width() - 1, height() - 1). This is similar to the conventional Cartesian coordinate system, but upside down, as Figure 5.3 illustrates. We can change QPainter's coordinate system by using transformations, such as translation, scaling, rotation, and shearing. We cover these in Chapter 8.

Before we call drawLine() on the QPainter, we set the line's color using setPen(). We could hard-code a color, such as black or gray, but a better approach is to use the widget's palette.

Every widget is equipped with a palette that specifies which colors should be used for what. For example, there is a palette entry for the background color of widgets (usually light gray) and one for the color of text on that background (usually black). By default, a widget's palette adopts the window system's color scheme. By using colors from the palette, we ensure that IconEditor respects the user's preferences.

A widget's palette consists of three color groups: active, inactive, and disabled. Which color group should be used depends on the widget's current state:

  • The Active group is used for widgets in the currently active window.
  • The Inactive group is used for widgets in the other windows.
  • The Disabled group is used for disabled widgets in any window.

The QWidget::palette() function returns the widget's palette as a QPalette object. Color groups are specified as enums of type QPalette::ColorGroup.

When we want to get an appropriate brush or color for drawing, the correct approach is to use the current palette, obtained from QWidget::palette(), and the required role, for example, QPalette::foreground(). Each role function returns a brush, which is normally what we want, but if we just need the color we can extract it from the brush, as we did in the paintEvent(). By default, the brushes returned are those appropriate to the widget's state, so we do not need to specify a color group.

The paintEvent() function finishes by drawing the image itself. The call to IconEditor::pixelRect() returns a QRect that defines the region to repaint. (Figure 5.4 illustrates how a rectangle is drawn.) As an easy optimization, we don't redraw pixels that fall outside this region.

Figure 5.4 Drawing a rectangle using

We call QPainter::fillRect() to draw a zoomed pixel. QPainter::fillRect() takes a QRect and a QBrush. By passing a QColor as the brush, we obtain a solid fill pattern. If the color isn't completely opaque (its alpha channel is less than 255), we draw a white background first.

The pixelRect() function returns a QRect suitable for QPainter::fillRect(). The i and j parameters are pixel coordinates in the QImage—not in the widget. If the zoom factor is 1, the two coordinate systems coincide exactly.

The QRect constructor has the syntax QRect(x, y, width, height), where (x, y) is the position of the top-left corner of the rectangle and width x height is the size of the rectangle. If the zoom factor is 3 or more, we reduce the size of the rectangle by one pixel horizontally and vertically so that the fill does not draw over the grid lines.

When the user presses a mouse button, the system generates a 'mouse press' event. By reimplementing QWidget::mousePressEvent(), we can respond to this event and set or clear the image pixel under the mouse cursor.

If the user pressed the left mouse button, we call the private function setImagePixel() with true as the second argument, telling it to set the pixel to the current pen color. If the user pressed the right mouse button, we also call setImagePixel(), but pass false to clear the pixel.

The mouseMoveEvent() handles 'mouse move' events. By default, these events are generated only when the user is holding down a button. It is possible to change this behavior by calling QWidget::setMouseTracking(), but we don't need to do so for this example.

Just as pressing the left or right mouse button sets or clears a pixel, keeping it pressed and hovering over a pixel is also enough to set or clear a pixel. Since it's possible to hold more than one button pressed down at a time, the value returned by QMouseEvent::buttons() is a bitwise OR of the mouse buttons. We test whether a certain button is pressed down using the & operator, and if this is the case we call setImagePixel().

The setImagePixel() function is called from mousePressEvent() and mouseMoveEvent() to set or clear a pixel. The pos parameter is the position of the mouse on the widget.

The first step is to convert the mouse position from widget coordinates to image coordinates. This is done by dividing the x() and y() components of the mouse position by the zoom factor. Next, we check whether the point is within the correct range. The check is easily made using QImage::rect() and QRect::contains(); this effectively checks that i is between 0 and image.width() - 1 and that j is between 0 and image.height() - 1.

Qt No Such Signal

Depending on the opaque parameter, we set or clear the pixel in the image. Clearing a pixel is really setting it to be transparent. We must convert the pen QColor to a 32-bit ARGB value for the QImage::setPixel() call. At the end, we call update() with a QRect of the area that needs to be repainted.

Now that we have reviewed the member functions, we will return to the Qt::WA_StaticContents attribute that we used in the constructor. This attribute tells Qt that the widget's content doesn't change when the widget is resized and that the content stays rooted to the widget's top-left corner. Qt uses this information to avoid needlessly repainting areas that are already shown when resizing the widget. This is illustrated by Figure 5.5.

Normally, when a widget is resized, Qt generates a paint event for the widget's entire visible area. But if the widget is created with the Qt::WA_StaticContents attribute, the paint event's region is restricted to the pixels that were not previously shown. This implies that if the widget is resized to a smaller size, no paint event is generated at all.

The IconEditor widget is now complete. Using the information and examples from earlier chapters, we could write code that uses the IconEditor as a window in its own right, as a central widget in a QMainWindow, as a child widget inside a layout, or as a child widget inside a QScrollArea. In the next section, we will see how to integrate it with Qt Designer.

Related Resources

  • Book $31.99
  • Book $35.99
  • Book $43.99