QApplication(3qt)
β¨ NAME β¨
QApplication(3qt) β bestie, this is the Qt class that manages the GUI application's control flow and main settings. It's literally the main character of your app's runtime. π
π SYNOPSIS π
Okay so first, you gotta include the header, and yes, it inherits QObject:
#include <qapplication.h>
Inherits QObject.
β¨ Public Members β¨
QApplication ( int & argc, char ** argv )
QApplication ( int & argc, char ** argv, bool GUIenabled )
enum Type { Tty, GuiClient, GuiServer }
QApplication ( int & argc, char ** argv, Type type )
QApplication ( Display * dpy, HANDLE visual = 0, HANDLE colormap = 0 )
QApplication ( Display * dpy, int argc, char ** argv, HANDLE visual = 0,
HANDLE colormap = 0 )
virtual ~QApplication ()
int argc () const
char ** argv () const
Type type () const
enum ColorSpec { NormalColor = 0, CustomColor = 1, ManyColor = 2 }
QWidget * mainWidget () const
virtual void setMainWidget ( QWidget * mainWidget )
virtual void polish ( QWidget * w )
QWidget * focusWidget () const
QWidget * activeWindow () const
int exec ()
void processEvents ()
void processEvents ( int maxtime )
void processOneEvent () (obsolete)
bool hasPendingEvents ()
int enter_loop () (obsolete)
void exit_loop () (obsolete)
int loopLevel () const (obsolete)
virtual bool notify ( QObject * receiver, QEvent * e )
void setDefaultCodec ( QTextCodec * codec ) (obsolete)
QTextCodec * defaultCodec () const (obsolete)
void installTranslator ( QTranslator * mf )
void removeTranslator ( QTranslator * mf )
enum Encoding { DefaultCodec, UnicodeUTF8 }
QString translate ( const char * context, const char * sourceText, const
char * comment = 0, Encoding encoding = DefaultCodec ) const
QString applicationDirPath ()
QString applicationFilePath ()
virtual bool macEventFilter ( EventHandlerCallRef, EventRef )
virtual bool winEventFilter ( MSG * )
virtual bool x11EventFilter ( XEvent * )
int x11ProcessEvent ( XEvent * event )
virtual bool qwsEventFilter ( QWSEvent * )
void qwsSetCustomColors ( QRgb * colorTable, int start, int numColors )
void winFocus ( QWidget * widget, bool gotFocus )
bool isSessionRestored () const
QString sessionId () const
QString sessionKey () const
virtual void commitData ( QSessionManager & sm )
virtual void saveState ( QSessionManager & sm )
void wakeUpGuiThread ()
void lock ()
void unlock ( bool wakeUpGui = TRUE )
bool locked ()
bool tryLock ()
π Public Slots π
void quit ()
void closeAllWindows ()
void aboutQt ()
π Signals π
void lastWindowClosed ()
void aboutToQuit ()
void guiThreadAwake ()
π Static Public Members π
QStyle & style ()
void setStyle ( QStyle * style )
QStyle * setStyle ( const QString & style )
int colorSpec ()
void setColorSpec ( int spec )
QCursor * overrideCursor ()
void setOverrideCursor ( const QCursor & cursor, bool replace = FALSE )
void restoreOverrideCursor ()
bool hasGlobalMouseTracking ()
void setGlobalMouseTracking ( bool enable )
QPalette palette ( const QWidget * w = 0 )
void setPalette ( const QPalette & palette, bool informWidgets = FALSE,
const char * className = 0 )
QFont font ( const QWidget * w = 0 )
void setFont ( const QFont & font, bool informWidgets = FALSE, const
char * className = 0 )
QFontMetrics fontMetrics ()
QWidgetList * allWidgets ()
QWidgetList * topLevelWidgets ()
QDesktopWidget * desktop ()
QWidget * activePopupWidget ()
QWidget * activeModalWidget ()
QClipboard * clipboard ()
QWidget * widgetAt ( int x, int y, bool child = FALSE )
QWidget * widgetAt ( const QPoint & pos, bool child = FALSE )
QEventLoop * eventLoop ()
void exit ( int retcode = 0 )
bool sendEvent ( QObject * receiver, QEvent * event )
void postEvent ( QObject * receiver, QEvent * event )
void sendPostedEvents ( QObject * receiver, int event_type )
void sendPostedEvents ()
void removePostedEvents ( QObject * receiver )
bool startingUp ()
bool closingDown ()
void flushX ()
void flush ()
void syncX ()
void beep ()
void setWinStyleHighlightColor ( const QColor & c ) (obsolete)
const QColor & winStyleHighlightColor () (obsolete)
void setDesktopSettingsAware ( bool on )
bool desktopSettingsAware ()
void setCursorFlashTime ( int msecs )
int cursorFlashTime ()
void setDoubleClickInterval ( int ms )
int doubleClickInterval ()
void setWheelScrollLines ( int n )
int wheelScrollLines ()
void setGlobalStrut ( const QSize & strut )
QSize globalStrut ()
void setLibraryPaths ( const QStringList & paths )
QStringList libraryPaths ()
void addLibraryPath ( const QString & path )
void removeLibraryPath ( const QString & path )
void setStartDragTime ( int ms )
int startDragTime ()
void setStartDragDistance ( int l )
int startDragDistance ()
void setReverseLayout ( bool b )
bool reverseLayout ()
int horizontalAlignment ( int align )
bool isEffectEnabled ( Qt::UIEffect effect )
void setEffectEnabled ( Qt::UIEffect effect, bool enable = TRUE )
QWSDecoration & qwsDecoration ()
void qwsSetDecoration ( QWSDecoration * d )
π RELATED FUNCTION DOCUMENTATION π
These are the related free functions, bestie β keep them close:
void qAddPostRoutine ( QtCleanUpFunction p )
const char * qVersion ()
bool qSysInfo ( int * wordSize, bool * bigEndian )
void qDebug ( const char * msg, ... )
void qWarning ( const char * msg, ... )
void qFatal ( const char * msg, ... )
void qSystemWarning ( const char * msg, int code )
void Q_ASSERT ( bool test )
void Q_CHECK_PTR ( void * p )
QtMsgHandler qInstallMsgHandler ( QtMsgHandler h )
π¦ DESCRIPTION π¦
The QApplication class manages the GUI application's control flow and main settings. That's the whole vibe. It's giving "app mom" energy. π
It contains the main event loop, where all events from the window system and other sources are processed and dispatched. It also handles the application's initialization and finalization, and provides session management. It also handles most system-wide and application-wide settings. So basically, it's running the whole show. π
For any GUI application that uses Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any time. One. Not two. Not zero. One. Fr fr.
The QApplication object is accessible through the global pointer qApp. Its main areas of responsibility are:
- It initializes the application with the user's desktop settings such as
palette(),font()anddoubleClickInterval(). 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()andpostEvent()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 about this. (Yes bestie, scroll down.)
- It defines the application's look and feel, which is encapsulated in a
QStyleobject. This can be changed at runtime withsetStyle(). π - 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 theclipboard(). Obsessed. - It knows about the application's windows. You can ask which widget is at a certain position using
widgetAt(), get a list oftopLevelWidgets()andcloseAllWindows(), etc. - It manages the application's mouse cursor handling, see
setOverrideCursor()andsetGlobalMouseTracking(). π±οΈ - On the X window system, it provides functions to flush and sync the communication stream, see
flushX()andsyncX(). - It provides support for sophisticated session management. This makes it possible for applications to terminate gracefully when the user logs out, to cancel a shutdown process if termination isn't possible and even to preserve the entire application's state for a future session. See
isSessionRestored(),sessionId()andcommitData()andsaveState()for details. π
The Application walk-through example contains a typical complete main() that does the usual things with QApplication. Go look at it if you need a template, bestie.
Since the QApplication object does so much initialization, it must be created before any other objects related to the user interface are created. No cap.
Since it also deals with common command line arguments, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself. (Note also that for X11, setMainWidget() may change the main widget according to the -geometry option. To preserve this functionality, you must set your defaults before setMainWidget() and any overrides after.) β οΈ
Also, the original page has this little formatting artifact right here: <center>.nf and </center>. No idea bestie, but it's in the source, so here it is. π
Non-GUI programs: While Qt is not optimized or designed for writing non-GUI programs, it's possible to use some of its classes without creating a QApplication. This can be useful if you wish to share code between a non-GUI server and a GUI client. That's actually kind of iconic. π
See also Main Window and Related Classes.
π Member Type Documentation π
QApplication::ColorSpec
QApplication::NormalColorβ the default color allocation policy.QApplication::CustomColorβ the same asNormalColorfor X11; allocates colors to a palette on demand under Windows.QApplication::ManyColorβ the right choice for applications that use thousands of colors.
See setColorSpec() for full details.
QApplication::Encoding
This enum type defines the 8-bit encoding of character string arguments to translate():
QApplication::DefaultCodecβ the encoding specified byQTextCodec::codecForTr()(Latin-1 if none has been set).QApplication::UnicodeUTF8β UTF-8.
See also QObject::tr(), QObject::trUtf8(), and QString::fromUtf8().
QApplication::Type
QApplication::Ttyβ a console application.QApplication::GuiClientβ a GUI client application.QApplication::GuiServerβ a GUI server application.
π MEMBER FUNCTION DOCUMENTATION π
π QApplication::QApplication ( int & argc, char ** argv )
Okay bestie, this is THE constructor. It sets up the whole window system and builds you an application object with argc command line args hanging out in argv. Iconic behavior, honestly. π
The global qApp pointer is gonna point at this application object, so likeβ¦ it's the main character. And only ONE application object should ever be created. One. Singular. Don't be greedy. π«Ά
Heads up: this application object has to be constructed before any paint devices β that means widgets, pixmaps, bitmaps, all of it. Paint devices don't exist yet, so don't try to summon them early.
Lowkey important: argc and argv might get changed. Qt yoinks out any command line arguments it recognizes (so rude of it, but ok). You can still peek at the modified versions later with qApp->argc() and qApp->argv(). And the docs for argv() have a whole detailed breakdown of how to process command line args, so go read that if you're curious. π
Qt debugging options β note these are NOT available if Qt was compiled with the QT_NO_DEBUG flag defined:
-nograbβ tells Qt it must NEVER grab the mouse or the keyboard. Ever. Hands off. π ββοΈ-dograbβ (only under X11) running under a debugger can cause an implicit-nograb, so use-dograbto override that. Sneaky.-syncβ (only under X11) switches to synchronous mode for debugging.
Check out Debugging Techniques for a more detailed explanation if you want the full tea. π
β¨ And get this β ALL Qt programs automatically support these command line options:
-reverseβ causes text to be formatted for right-to-left languages instead of the usual left-to-right direction. Flipped, slay.-style=style β sets the application GUI style. Possible values aremotif,windows, andplatinum. If you compiled Qt with additional styles, or you've got extra styles as plugins, those become available to the-stylecommand line option too. Fancy.-stylestyle β same thing as above, just with a space instead of an equals sign. Same energy. π-session=session β restores the application from an earlier session. Blast from the past.-sessionsession β again, same as above, space edition.-widgetcountβ prints a debug message at the end about the number of widgets left undestroyed AND the maximum number of widgets that existed at the same time. Receipts at the end. π
The X11 version of Qt also supports some traditional X11 command line options, because X11 loves options:
-displaydisplay β sets the X display (default is$DISPLAY).-geometrygeometry β sets the client geometry of the main widget.-fnor-fontfont β defines the application font. The font should be specified using an X logical font description.-bgor-backgroundcolor β sets the default background color and an application palette (light and dark shades are calculated).-fgor-foregroundcolor β sets the default foreground color.-btnor-buttoncolor β sets the default button color.-namename β sets the application name.-titletitle β sets the application title (caption).-visual TrueColorβ forces the application to use a TrueColor visual on an 8-bit display.-ncolscount β limits the number of colors allocated in the color cube on an 8-bit display, but only if the application is using theQApplication::ManyColorcolor specification. If count is216then a6x6x6color cube is used (that's 6 levels of red, 6 of green, and 6 of blue). For other values, a cube approximately proportional to a2x3x1cube is used.-cmapβ causes the application to install a private color map on an 8-bit display.
See also argc() and argv(). β¨
π QApplication::QApplication ( int & argc, char ** argv, bool GUIenabled )
Constructs an application object with argc command line arguments in argv. If GUIenabled is TRUE, you get a GUI application. If it's not, you get a non-GUI (console) application. Pick your fighter. π₯
Set GUIenabled to FALSE for programs without a graphical user interface that should be able to run without a window system. Headless queen behavior. π
On X11, the window system gets initialized if GUIenabled is TRUE. If GUIenabled is FALSE, the application does NOT connect to the X-server. On Windows and Macintosh, though β currently the window system is always initialized, regardless of the value of GUIenabled. This may change in future versions of Qt, so like, stay tuned I guess. π
Here's an example showing how to create an application that uses a graphical interface when available:
int main( int argc, char **argv )
{
#ifdef Q_WS_X11
bool useGUI = getenv( "DISPLAY" ) != 0;
#else
bool useGUI = TRUE;
#endif
QApplication app(argc, argv, useGUI);
if ( useGUI ) {
//start GUI version
...
} else {
//start non-GUI version
...
}
return app.exec();
}
π¦ QApplication::QApplication ( int & argc, char ** argv, Type type )
Constructs an application object with argc command line arguments in argv. That's it, that's the vibe.
For Qt/Embedded, passing QApplication::GuiServer for type makes this application the server β which is equivalent to running with the -qws option. Server era. π
πΈ QApplication::QApplication ( Display * dpy, HANDLE visual = 0, HANDLE colormap = 0 )
Creates an application, given an already open display dpy. If visual and colormap are non-zero, the application will use those as the default Visual and Colormap contexts. Plug it in, plug it in. π
Warning: Qt only supports TrueColor visuals at depths higher than 8 bits-per-pixel.
This one is available only on X11.
π QApplication::QApplication ( Display * dpy, int argc, char ** argv, HANDLE visual = 0, HANDLE colormap = 0 )
Creates an application, given an already open display dpy, and using argc command line arguments in argv. If visual and colormap are non-zero, the application will use those as the default Visual and Colormap contexts. Same deal as the one above, just with command line args in the mix now.
Warning: Qt only supports TrueColor visuals at depths higher than 8 bits-per-pixel.
Also available only on X11. π«Ά
π§ QApplication::~QApplication () [virtual]
Cleans up any window system resources that were allocated by this application. And it sets the global variable qApp to 0. Goodbye bestie, you served. π₯Ή
β¨ void QApplication::aboutQt () [slot]
Displays a simple message box about Qt. The message includes the version number of Qt being used by the application. Cute little info popup. π
This is useful for inclusion in the Help menu of an application β check out the examples/menu/menu.cpp example for how it's done.
This function is a convenience slot for QMessageBox::aboutQt(). iykyk.
π₯Ή void QApplication::aboutToQuit () [signal]
This signal is emitted when the application is about to quit the main event loop, e.g. when the event loop level drops to zero. This can happen either after a call to quit() from inside the application, or when the user shuts down the entire desktop session. Either way, it's giving last-call energy. π°οΈ
The signal is particularly useful if your application has to do some last-second cleanup. But note that no user interaction is possible in this state β you can't pop up a dialog and ask the user anything, it's over bestie. π
See also quit().
π QWidget * QApplication::activeModalWidget () [static]
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. It's the "no, we're doing THIS first" of widgets.
Modal widgets are organized in a stack, and this function returns the active modal widget at the top of the stack. Main character at the front of the line. π
See also activePopupWidget() and topLevelWidgets().
π QWidget * QApplication::activePopupWidget () [static]
Returns the active popup widget.
A popup widget is a special top level widget that sets the WType_Popup widget flag β e.g. the QPopupMenu 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. It's the ultimate vibe check. π«
Only other popup widgets may be opened when a popup widget is shown. The popup widgets are organized in a stack, and this function returns the active popup widget at the top of the stack. Same stack energy as the modal one.
See also activeModalWidget() and topLevelWidgets().
π QWidget * QApplication::activeWindow () const
Returns the application top-level window that has the keyboard input focus, or 0 if no application window has the focus. Keyboard attention = this window. β¨οΈ
Note that there might be an activeWindow() even if there is no focusWidget() β for example if no widget in that window accepts key events. So don't get confused, they're not the same thing bestie.
See also QWidget::setFocus(), QWidget::focus, and focusWidget().
Example: network/mail/smtp.cpp.
π void QApplication::addLibraryPath ( const QString & path ) [static]
Append path to the end of the library path list. If path is empty, or already in the path list, the path list is not changed. No duplicates, no empties, no problem. π«Ά
The default path list consists of a single entry β the installation directory for plugins. The default installation directory for plugins is INSTALL/plugins, where INSTALL is the directory where Qt was installed.
See also removeLibraryPath(), libraryPaths(), and setLibraryPaths().
β QWidgetList * QApplication::allWidgets () [static]
Returns a list of ALL the widgets in the application. Every single one. Gather the whole squad. π
The list is created using new and must be deleted by the caller. Your list, your responsibility.
The list is empty (QPtrList::isEmpty()) if there are no widgets.
Note that some of the widgets may be hidden. Sneaky little hidden ones. π
Here's an example that updates all widgets:
QWidgetList *list = QApplication::allWidgets();
QWidgetListIt it( *list ); // iterate over the widgets
QWidget * w;
while ( (w=it.current()) != 0 ) { // for each widget...
++it;
w->update();
}
delete list; // delete the list, not the widgets
The QWidgetList class is defined in the qwidgetlist.h header file.
Warning: Delete the list as soon as you have finished using it. The widgets in the list may be deleted by someone else at any time. π
See also topLevelWidgets(), QWidget::visible, and QPtrList::isEmpty().
πΈ QString QApplication::applicationDirPath ()
Returns the directory that contains the application executable. π
For example, if you have installed Qt in the C:\Trolltech\Qt directory, and you run the demo example, this function will return "C:/Trolltech/Qt/examples/demo". Slashes and everything, iconic.
On Mac OS X this will point to the directory actually containing the executable, which may be inside of an application bundle (if the application is bundled). Bundle bestie. π
Warning: On Unix, this function assumes that argv[0] contains the file name of the executable (which it normally does). It also assumes that the current directory hasn't been changed by the application. So like⦠don't move directories on it, ok?
See also applicationFilePath().
π¦ QString QApplication::applicationFilePath ()
Returns the file path of the application executable. The whole shebang, file included. π
For example, if you have installed Qt in the C:\Trolltech\Qt directory, and you run the demo example, this function will return "C:/Trolltech/Qt/examples/demo/demo.exe". Full path, no cap.
Warning: On Unix, this function assumes that argv[0] contains the file name of the executable (which it normally does). It also assumes that the current directory hasn't been changed by the application. Same warning, same energy. π
See also applicationDirPath().
π
int QApplication::argc () const
Returns the number of command line arguments. Just the count, bestie. π’
The documentation for argv() describes how to process command line arguments, so head there for the details.
See also argv() and QApplication::QApplication().
Examples:
char ** QApplication::argv () const
Returns the command line argument vector. It's giving β¨the receiptsβ¨ of how your program was launched.
So like, argv()[0] is the program name, argv()[1] is the first argument, and argv()[argc()-1] is the last argument. Bestie math π
A QApplication object gets constructed by passing argc and argv straight from your main() function. And here's the tea: some of those arguments might get recognized as Qt options and removed from the argument vector. Like, the X11 version of Qt knows about -display, -font and a few more options. Not me gatekeeping your args π
Example:
// showargs.cpp - displays program arguments in a list box
#include <qapplication.h>
#include <qlistbox.h>
int main( int argc, char **argv )
{
QApplication a( argc, argv );
QListBox b;
a.setMainWidget( &b );
for ( int i = 0; i < a.argc(); i++ ) // a.argc() == argc
b.insertItem( a.argv()[i] ); // a.argv()[i] == argv[i]
b.show();
return a.exec();
}
If you run showargs -display unix:0 -font 9x15bold hello world under X11, the list box contains the three strings "showargs"," hello" and "world".
Qt provides a global pointer, qApp, that points to the QApplication object, and through which you can access argc() and argv() in functions other than main(). Lowkey iconic πΈ
See also argc() and QApplication::QApplication().
Examples:
void QApplication::beep () [static]
Sounds the bell, using the default volume and sound. Just a lil π moment, no cap.
QClipboard * QApplication::clipboard () [static]
Returns a pointer to the application global clipboard. Copy-paste queens, this one's for you π β¨
Examples:
void QApplication::closeAllWindows () [slot]
Closes all top-level windows. The ultimate "okay everyone go home" π
This function is particularly useful for applications with many top-level windows. It could, for example, be connected to a "Quit" entry in the file menu as shown in the following code example:
// the "Quit" menu entry should try to close all windows
QPopupMenu* file = new QPopupMenu( this );
file->insertItem( "&Quit", qApp, SLOT(closeAllWindows()), CTRL+Key_Q );
// when the last window is closed, the application should quit
connect( qApp, SIGNAL( lastWindowClosed() ), qApp, SLOT( quit() ) );
The windows are closed in random order, until one window does not accept the close event. Yes, random. Chaos behavior fr fr π²
See also QWidget::close(), QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(), and QWidget::isTopLevel.
Examples:
bool QApplication::closingDown () [static]
Returns TRUE if the application objects are being destroyed; otherwise returns FALSE. It's giving "are we so back or are we done" π
See also startingUp().
int QApplication::colorSpec () [static]
Returns the color specification. π
See also QApplication::setColorSpec().
Example: showimg/showimg.cpp.
void QApplication::commitData ( QSessionManager & sm ) [virtual]
This function deals with session management. It is invoked when the QSessionManager wants the application to commit all its data. Like "bestie, save everything, we're going down" π
Usually this means saving all open files, after getting permission from the user. Furthermore you may want to provide a means by which the user can cancel the shutdown. Consent matters, always π«Ά
Note that you should not exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context.
Warning: Within this function, no user interaction is possible, unless you ask the session manager sm for explicit permission. SeeQSessionManager::allowsInteraction()andQSessionManager::allowsErrorInteraction()for details and example usage. Like, you literally cannot talk to the user without a hall pass, okay?
The default implementation requests interaction and sends a close event to all visible top level widgets. If any event was rejected, the shutdown is canceled.
See also isSessionRestored(), sessionId(), saveState(), and the Session Management overview.
int QApplication::cursorFlashTime () [static]
Returns the text cursor's flash (blink) time in milliseconds. The flash time is the time required to display, invert and restore the caret display. That lil blinking line living its best life β¨
The default value on X11 is 1000 milliseconds. On Windows, the control panel value is used.
Widgets should not cache this value since it may be changed at any time by the user changing the global desktop settings. Do not be out here storing stale numbers, bestie π
See also setCursorFlashTime().
QTextCodec * QApplication::defaultCodec () const
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. It's giving legacy, and not in a cute way π
Returns QTextCodec::codecForTr().
QDesktopWidget * QApplication::desktop () [static]
Returns the desktop widget (also called the root window). The main character of your screen π
The desktop widget is useful for obtaining the size of the screen. It may also be possible to draw on the desktop. We recommend against assuming that it's possible to draw on the desktop, since this does not work on all operating systems.
QDesktopWidget *d = QApplication::desktop();
int w = d->width(); // returns desktop width
int h = d->height(); // returns desktop height
Examples:
bool QApplication::desktopSettingsAware () [static]
Returns the value set by setDesktopSettingsAware(); by default TRUE. Defaults stay slaying π
See also setDesktopSettingsAware().
int QApplication::doubleClickInterval () [static]
Returns the maximum duration for a double click. You know, that window where two taps count as one vibe βοΈ
The default value on X11 is 400 milliseconds. On Windows, the control panel value is used.
See also setDoubleClickInterval().
int QApplication::enter_loop ()
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. Bestie, put it down π«³
This function enters the main event loop (recursively). Do not call it unless you really know what you are doing. No cap, this is expert-level territory.
Use QApplication::eventLoop()->enterLoop() instead.
QEventLoop * QApplication::eventLoop () [static]
Returns the application event loop. This function will return zero if called during and after destroying QApplication. Timing is everything, periodt β°
To create your own instance of QEventLoop or QEventLoop subclass create it before you create the QApplication object.
See also QEventLoop.
Example: distributor/distributor.ui.h.
int QApplication::exec ()
Enters the main event loop and waits until exit() is called or the main widget is destroyed, and returns the value that was set to exit() (which is 0 if exit() is called via quit()). This is the moment your app actually starts, bestie π₯
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 speaking, 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().
See also quit(), exit(), processEvents(), and setMainWidget().
Examples:
void QApplication::exit ( int retcode = 0 ) [static]
Tells the application to exit with a return code.
After this function has been called, the application leaves the main event loop and returns from the call to exec(). The exec() function returns retcode.
By convention, a retcode of 0 means success, and any non-zero value indicates an error. Zero = slay, anything else = we have problems π
Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.
See also quit() and exec().
Examples:
void QApplication::exit_loop ()
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. Old news, bestie π
This function exits from a recursive call to the main event loop. Do not call it unless you are an expert.
Use QApplication::eventLoop()->exitLoop() instead.
void QApplication::flush () [static]
Flushes the window system specific event queues.
If you are doing graphical changes inside a loop that does not return to the event loop on asynchronous window systems like X11 or double buffered window systems like MacOS X, and you want to visualize these changes immediately (e.g. Splash Screens), call this function. Splash screens deserve their moment π
See also flushX(), sendPostedEvents(), and QPainter::flush().
void QApplication::flushX () [static]
Flushes the X event queue in the X11 implementation. This normally returns almost immediately. Does nothing on other platforms. She's fast and she's X11-only π
See also syncX().
Example: xform/xform.cpp.
QWidget * QApplication::focusWidget () const
Returns the application widget that has the keyboard input focus, or 0 if no widget in this application has the focus. Keyboard main character energy β¨οΈπ
See also QWidget::setFocus(), QWidget::focus, and activeWindow().
QFont QApplication::font ( const QWidget * w = 0 ) [static]
Returns the default font for the widget w, or the default application font if w is 0.
See also setFont(), fontMetrics(), and QWidget::font.
Examples:
QFontMetrics QApplication::fontMetrics () [static]
Returns display (screen) font metrics for the application font. Numbers about letters, very demure β¨
See also font(), setFont(), QWidget::fontMetrics(), and QPainter::fontMetrics().
QSize QApplication::globalStrut () [static]
Returns the application's global strut.
The strut is a size object whose dimensions are the minimum 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. Respect the strut, bestie π
See also setGlobalStrut().
void QApplication::guiThreadAwake () [signal]
This signal is emitted after the event loop returns from a function that could block. Waking up refreshed, we love to see it βοΈ
See also wakeUpGuiThread().
bool QApplication::hasGlobalMouseTracking () [static]
Returns TRUE if global mouse tracking is enabled; otherwise returns FALSE. Is the mouse everywhere? Vibe check π
See also setGlobalMouseTracking().
bool QApplication::hasPendingEvents ()
This function returns TRUE if there are pending events; otherwise returns FALSE. Pending events can be either from the window system or posted events using QApplication::postEvent().
int QApplication::horizontalAlignment ( int align ) [static]
Strips out vertical alignment flags and transforms an alignment align of AlignAuto into AlignLeft or AlignRight according to the language used. The other horizontal alignment flags are left untouched. Left-to-right besties and right-to-left besties both get what they need π«Ά
void QApplication::installTranslator ( QTranslator * mf )
Adds the message file mf to the list of message files to be used for translations. i18n girlies rise π
Multiple message files can be installed. Translations are searched for in the last installed message file, then the one from last, and so on, back to the first installed message file. The search stops as soon as a matching translation is found. Newest in, first checked β very much last-installed-wins energy β¨
See also removeTranslator(), translate(), and QTranslator::load().
Example: i18n/main.cpp.
bool QApplication::isEffectEnabled ( Qt::UIEffect effect ) [static]
Returns TRUE if effect is enabled; otherwise returns FALSE. β¨
By default, Qt will try to use the desktop settings. Call setDesktopSettingsAware(FALSE) to prevent this.
Note: All effects are disabled on screens running at less than 16-bit color depth. π
See also setEffectEnabled() and Qt::UIEffect.
bool QApplication::isSessionRestored () const
Returns TRUE if the application has been restored from an earlier session; otherwise returns FALSE. π¦
See also sessionId(), commitData(), and saveState().
void QApplication::lastWindowClosed () [signal]
This signal is emitted when the user has closed the last top level window. π
The signal is very useful when your application has many top level widgets but no main widget. You can then connect it to the quit() slot.
For convenience, this signal is not emitted for transient top level widgets such as popup menus and dialogs.
See also mainWidget(), topLevelWidgets(), QWidget::isTopLevel, and QWidget::close().
Examples:
QStringList QApplication::libraryPaths () [static]
Returns a list of paths that the application will search when dynamically loading libraries. The installation directory for plugins is the only entry if no paths have been set. The default installation directory for plugins is INSTALL/plugins, where INSTALL is the directory where Qt was installed. The directory of the application executable (NOT the working directory) is also added to the plugin paths. π
If you want to iterate over the list, you should iterate over a copy, e.g.
QStringList list = app.libraryPaths();
QStringList::Iterator it = list.begin();
while( it != list.end() ) {
myProcessing( *it );
++it;
}
See the plugins documentation for a description of how the library paths are used.
See also setLibraryPaths(), addLibraryPath(), removeLibraryPath(), and QLibrary.
void QApplication::lock ()
Lock the Qt Library Mutex. If another thread has already locked the mutex, the calling thread will block until the other thread has unlocked the mutex. π
See also unlock(), locked(), and Thread Support in Qt.
bool QApplication::locked ()
Returns TRUE if the Qt Library Mutex is locked by a different thread; otherwise returns FALSE.
Warning: Due to different implementations of recursive mutexes on the supported platforms, calling this function from the same thread that previously locked the mutex will give undefined results. π
See also lock(), unlock(), and Thread Support in Qt.
int QApplication::loopLevel () const
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.
Returns the current loop level.
Use QApplication::eventLoop()->loopLevel() instead. π
bool QApplication::macEventFilter ( EventHandlerCallRef, EventRef ) [virtual]
This virtual function is only implemented under Macintosh. π
If you create an application that inherits QApplication and reimplement this function, you get direct access to all Carbon Events that are received from the MacOS.
Return TRUE if you want to stop the event from being processed. Return FALSE for normal event dispatching.
QWidget * QApplication::mainWidget () const
Returns the main application widget, or 0 if there is no main widget.
See also setMainWidget().
bool QApplication::notify ( QObject * receiver, QEvent * e ) [virtual]
Sends event e to receiver: receiver->event(e). Returns the value that is returned from the receiver's event handler. π¨
For certain types of events (e.g. mouse and key events), the event will be propagated to the receiver's parent and so on up to the top-level object if the receiver is not interested in the event (i.e., it returns FALSE).
There are five different ways that events can be processed; reimplementing this virtual function is just one of them. All five approaches are listed below:
- Reimplementing this function. This is very powerful, providing complete control; but only one subclass can be
qApp. - Installing an event filter on
qApp. Such an event filter is able to process all events for all widgets, so it's just as powerful as reimplementingnotify(); furthermore, it's possible to have more than one application-global event filter. Global event filters even see mouse events for disabled widgets, and if global mouse tracking is enabled, as well as mouse move events for all widgets. - Reimplementing
QObject::event()(asQWidgetdoes). If you do this you get Tab key presses, and you get to see the events before any widget-specific event filters. - Installing an event filter on the object. Such an event filter gets all the events except Tab and Shift-Tab key presses.
- Reimplementing
paintEvent(),mousePressEvent()and so on. This is the commonest, easiest and least powerful way. π
See also QObject::event() and installEventFilter().
QCursor * QApplication::overrideCursor () [static]
Returns the active application override cursor.
This function returns 0 if no application cursor has been defined (i.e. the internal cursor stack is empty). π
See also setOverrideCursor() and restoreOverrideCursor().
QPalette QApplication::palette ( const QWidget * w = 0 ) [static]
Returns the application palette. π
If a widget is passed in w, the default palette for the widget's class is returned. This may or may not be the application palette. In most cases there isn't a 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.
Examples:
void QApplication::polish ( QWidget * w ) [virtual]
Initialization of the appearance of the widget w before it is first shown. β¨
Usually widgets call this automatically when they are polished. It may be used to do some style-based central customization of widgets.
Note that you are not limited to the public functions of QWidget. Instead, based on meta information like QObject::className() you are able to customize any kind of widget.
See also QStyle::polish(), QWidget::polish(), setPalette(), and setFont().
void QApplication::postEvent ( QObject * receiver, QEvent * event ) [static]
Note: This function is thread-safe when Qt is built with thread support.
Adds the event event with the object receiver as the receiver of the event, to an event queue and returns immediately. π¬
The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted.
When control returns to the main event loop, all events that are stored in the queue will be sent using the notify() function.
See also sendEvent() and notify().
void QApplication::processEvents ()
Processes pending events, for 3 seconds or until there are no more events to process, whichever is shorter. β³
You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file).
See also exec(), QTimer, and QEventLoop::processEvents().
Examples:
void QApplication::processEvents ( int maxtime )
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Processes pending events for maxtime milliseconds or until there are no more events to process, whichever is shorter.
You can call this function occasionally when you program is busy doing a long operation (e.g. copying a file). π«Ά
See also exec(), QTimer, and QEventLoop::processEvents().
void QApplication::processOneEvent ()
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.
Waits for an event to occur, processes it, then returns.
This function is useful for adapting Qt to situations where the event processing must be grafted onto existing program loops.
Using this function in new applications may be an indication of design problems. π
See also processEvents(), exec(), and QTimer.
void QApplication::quit () [slot]
Tells the application to exit with return code 0 (success). Equivalent to calling QApplication::exit( 0 ). π
It's common to connect the lastWindowClosed() signal to quit(), and you also often connect e.g. QButton::clicked() or signals in QAction, QPopupMenu or QMenuBar to it.
Example:
QPushButton *quitButton = new QPushButton( "Quit" );
connect( quitButton, SIGNAL(clicked()), qApp, SLOT(quit()) );
See also exit(), aboutToQuit(), lastWindowClosed(), and QAction.
Examples:
QWSDecoration & QApplication::qwsDecoration () [static]
Return the QWSDecoration used for decorating windows.
This method is non-portable. It is available only in Qt/Embedded. π§
See also QWSDecoration.
bool QApplication::qwsEventFilter ( QWSEvent * ) [virtual]
This virtual function is only implemented under Qt/Embedded.
If you create an application that inherits QApplication and reimplement this function, you get direct access to all QWS (Q Window System) events that the are received from the QWS master process.
Return TRUE if you want to stop the event from being processed. Return FALSE for normal event dispatching.
void QApplication::qwsSetCustomColors ( QRgb * colorTable, int start, int numColors )
Set Qt/Embedded custom color table. π¨
Qt/Embedded on 8-bpp displays allocates a standard 216 color cube. The remaining 40 colors may be used by setting a custom color table in the QWS master process before any clients connect.
colorTable is an array of up to 40 custom colors. start is the starting index (0-39) and numColors is the number of colors to be set (1-40).
This method is non-portable. It is available only in Qt/Embedded.
void QApplication::qwsSetDecoration ( QWSDecoration * d ) [static]
Set the QWSDecoration derived class to use for decorating the Qt/Embedded windows to d.
This method is non-portable. It is available only in Qt/Embedded. π
See also QWSDecoration.
void QApplication::removeLibraryPath ( const QString & path ) [static]
Removes path from the library path list. If path is empty or not in the path list, the list is not changed.
See also addLibraryPath(), libraryPaths(), and setLibraryPaths().
void QApplication::removePostedEvents ( QObject * receiver ) [static]
Note: This function is thread-safe when Qt is built with thread support.
Removes all events posted using postEvent() for receiver. ποΈ
The events are not dispatched, instead they are removed from the queue. You should never need to call this function. If you do call it, be aware that killing events may cause receiver to break one or more invariants. π
void QApplication::removeTranslator ( QTranslator * mf )
Ok so this is the β¨undoβ¨ button for translators. It takes the message file mf and yeets it out of the list of message files your app is using. That's it. That's the whole vibe.
Heads up bestie: it does NOT delete the message file from the file system. It just stops using it. Your .qm file is still sitting there, thriving, unbothered. π
See also installTranslator(), translate(), and QObject::tr().
Example: i18n/main.cpp.
void QApplication::restoreOverrideCursor () [static]
Undoes the last setOverrideCursor(). Basically the "jk bestie, nevermind" of cursor functions. π
Here's the tea though: if setOverrideCursor() has been called twice, calling restoreOverrideCursor() will activate the first cursor set. And calling this function a second time restores the original widgets' cursors. So it's a little stack, lowkey. π«Ά
See also setOverrideCursor() and overrideCursor().
Examples:
bool QApplication::reverseLayout () [static]
Returns TRUE if all dialogs and widgets will be laid out in a mirrored (right to left) fashion. Returns FALSE if dialogs and widgets will be laid out left to right. β¨
See also setReverseLayout().
void QApplication::saveState ( QSessionManager & sm ) [virtual]
This one is the session management girly. It gets invoked when the session manager wants your app to preserve its state for a future session. So like, remembering things. Memory queen. π
Example vibe: a text editor would create a temporary file that includes the current contents of its edit buffers, the location of the cursor and other aspects of the current editing session. Cute, right? π¦
Note: you should never exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context. Furthermore, most session managers will very likely request a saved state immediately after the application has been started. This permits the session manager to learn about the application's restart policy.
Warning: within this function, no user interaction is possible, unless you ask the session managersmfor explicit permission. SeeQSessionManager::allowsInteraction()andQSessionManager::allowsErrorInteraction()for details. No chatting with the user in here, periodt. π
See also isSessionRestored(), sessionId(), commitData(), and the Session Management overview.
bool QApplication::sendEvent ( QObject * receiver, QEvent * event ) [static]
Sends event event directly to receiver receiver, using the notify() function. Returns the value that was returned from the event handler. Direct. No queue, no waiting, straight to the target. π
The event is not deleted when the event has been sent. The normal approach is to create the event on the stack, like:
QMouseEvent me( QEvent::MouseButtonPress, pos, 0, 0 );
QApplication::sendEvent( mainWindow, &me );
And if you create the event on the heap? You must delete it. Don't forget, bestie, that's a leak. π
See also postEvent() and notify().
Example: popup/popup.cpp.
void QApplication::sendPostedEvents ( QObject * receiver, int event_type ) [static]
Immediately dispatches all events which have been previously queued with QApplication::postEvent() and which are for the object receiver and have the event type event_type. It's the "okay we're doing these ones RIGHT NOW" function. β‘
Note that events from the window system are not dispatched by this function β those go through processEvents() instead. Different lane, different vibe. π¦
- If
receiveris null, the events ofevent_typeare sent for all objects. - If
event_typeis0, all the events are sent forreceiver.
void QApplication::sendPostedEvents () [static]
This is an overloaded member function, provided for convenience. It behaves essentially like the above function. π«Ά
Dispatches all posted events, i.e. empties the event queue. Clean slate energy. β¨
QString QApplication::sessionId () const
Returns the current session's identifier. πͺͺ
If the application has been restored from an earlier session, this identifier is the same as it was in that previous session.
And the session identifier is guaranteed to be unique both for different applications and for different instances of the same application. Iconic and one of a kind, no cap. π
See also isSessionRestored(), sessionKey(), commitData(), and saveState().
QString QApplication::sessionKey () const
Returns the session key in the current session. π
If the application has been restored from an earlier session, this key is the same as it was when the previous session ended.
But here's the thing β the session key changes with every call of commitData() or saveState(). So it's not a fixed identifier, it's a lil moving target. π
See also isSessionRestored(), sessionId(), commitData(), and saveState().
void QApplication::setColorSpec ( int spec ) [static]
Sets the color specification for the application to spec. π
The color specification controls how the application allocates colors when run on a display with a limited amount of colors, e.g. 8 bit / 256 color displays.
Important: the color specification must be set before you create the QApplication object. Before. Not after. Timing matters, bestie. β°
The options are:
QApplication::NormalColorβ this is the default color allocation strategy. Use this option if your application uses buttons, menus, texts and pixmaps with few colors. With this option, the application uses system global colors. This works fine for most applications under X11, but on Windows machines it may cause dithering of non-standard colors.QApplication::CustomColorβ use this option if your application needs a small number of custom colors. On X11, this option is the same asNormalColor. On Windows, Qt creates a Windows palette, and allocates colors to it on demand.QApplication::ManyColorβ use this option if your application is very color hungry (e.g. it requires thousands of colors). Under X11 the effect is:- For 256-color displays which have at best a 256 color true color visual, the default visual is used, and colors are allocated from a color cube. The color cube is the 6x6x6 (216 color) "Web palette"<sup>*</sup>, but the number of colors can be changed by the
-ncolsoption. The user can force the application to use the true color visual with the-visualoption. - For 256-color displays which have a true color visual with more than 256 colors, use that visual. Silicon Graphics X servers have this feature, for example. They provide an 8 bit visual by default but can deliver true color when asked. On Windows, Qt creates a Windows palette, and fills it with a color cube.
- For 256-color displays which have at best a 256 color true color visual, the default visual is used, and colors are allocated from a color cube. The color cube is the 6x6x6 (216 color) "Web palette"<sup>*</sup>, but the number of colors can be changed by the
Be aware that the CustomColor and ManyColor choices may lead to colormap flashing: the foreground application gets (most) of the available colors, while the background windows will look less attractive. It's giving main character app, side character windows. π
Example:
int main( int argc, char **argv )
{
QApplication::setColorSpec( QApplication::ManyColor );
QApplication a( argc, argv );
...
}
QColor provides more functionality for controlling color allocation and freeing up certain colors. See QColor::enterAllocContext() for more information.
To check what mode you end up with, call QColor::numBitPlanes() once the QApplication object exists. A value greater than 8 (typically 16, 24 or 32) means true color. π
<sup>*</sup> The color cube used by Qt has 216 colors whose red, green, and blue components always have one of the following values: 0x00, 0x33, 0x66, 0x99, 0xCC, or 0xFF.
See also colorSpec(), QColor::numBitPlanes(), and QColor::enterAllocContext().
Examples:
void QApplication::setCursorFlashTime ( int msecs ) [static]
Sets the text cursor's flash (blink) time to msecs milliseconds. β±οΈ The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for msecs/2 milliseconds, then hidden for msecs/2 milliseconds, but this may vary. So it's a blink half and half situation. π
Note: on Microsoft Windows, calling this function sets the cursor flash time for all windows.
See also cursorFlashTime().
void QApplication::setDefaultCodec ( QTextCodec * codec )
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. π«
This is the same as QTextCodec::setCodecForTr(). That's the whole thing. Move along, bestie. π
void QApplication::setDesktopSettingsAware ( bool on ) [static]
By default, Qt will try to use the current standard colors, fonts etc., from the underlying window system's desktop settings, and use them for all relevant widgets. This behavior can be switched off by calling this function with on set to FALSE. π
Important: this static function must be called before creating the QApplication object, like this:
int main( int argc, char** argv ) {
QApplication::setDesktopSettingsAware( FALSE ); // I know better than the user
QApplication myApp( argc, argv ); // Use default fonts & colors
...
}
See also desktopSettingsAware().
void QApplication::setDoubleClickInterval ( int ms ) [static]
Sets the time limit that distinguishes a double click from two consecutive mouse clicks to ms milliseconds. So this is literally the function that decides whether your taps count as one thing or two. The power. π
Note: on Microsoft Windows, calling this function sets the double click interval for all windows.
See also doubleClickInterval().
void QApplication::setEffectEnabled ( Qt::UIEffect effect, bool enable = TRUE ) [static]
Enables the UI effect effect if enable is TRUE, otherwise the effect will not be used. Sparkle on or sparkle off, your call. β¨
Note: all effects are disabled on screens running at less than 16-bit color depth.
See also isEffectEnabled(), Qt::UIEffect, and setDesktopSettingsAware().
void QApplication::setFont ( const QFont & font, bool informWidgets = FALSE, const char * className = 0 ) [static]
Changes the default application font to font. π
- If
informWidgetsisTRUE, then existing widgets are informed about the change and may adjust themselves to the new application setting. - If
informWidgetsisFALSE, the change only affects newly created widgets. - If
classNameis passed, the change applies only to classes that inheritclassName(as reported byQObject::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. So like, respect the locale, bestie. π«Ά
See also font(), fontMetrics(), and QWidget::font.
Examples:
void QApplication::setGlobalMouseTracking ( bool enable ) [static]
Enables global mouse tracking if enable is TRUE, or disables it if enable is FALSE. π±οΈ
Enabling global mouse tracking makes it possible for widget event filters or application event filters to get all mouse move events, even when no button is depressed. This is useful for special GUI elements, e.g. tooltips. Iconic, honestly. π
Global mouse tracking does not affect widgets and their mouseMoveEvent(). For a widget to get mouse move events when no button is depressed, it must do QWidget::setMouseTracking(TRUE). Different thing, don't mix them up. π
This function uses an internal counter. Each setGlobalMouseTracking(TRUE) must have a corresponding setGlobalMouseTracking(FALSE):
// at this point global mouse tracking is off
QApplication::setGlobalMouseTracking( TRUE );
QApplication::setGlobalMouseTracking( TRUE );
QApplication::setGlobalMouseTracking( FALSE );
// at this point it's still on
QApplication::setGlobalMouseTracking( FALSE );
// but now it's off
See also hasGlobalMouseTracking() and QWidget::mouseTracking.
void QApplication::setGlobalStrut ( const QSize & strut )[static] β bestie, this one sets the application's global strut to strut π
The strut is a size object whose dimensions are the minimum that any GUI element the user can actually interact with should have. Like, imagine a button getting squished smaller than the global strut size? Not on our watch. π ββοΈ
You should lowkey keep the strut size in mind when you're reimplementing GUI controls that might get used on touch-screens or similar IO-devices β tiny tap targets are a crime fr.
Example:
QSize& WidgetClass::sizeHint() const
{
return QSize( 80, 25 ).expandedTo( QApplication::globalStrut() );
}
See also globalStrut().
void QApplication::setLibraryPaths ( const QStringList & paths )[static] β sets the list of directories to search when loading libraries to paths. Every existing path gets deleted, and the path list becomes exactly the paths you handed over in paths. Clean slate energy β¨
See also libraryPaths(), addLibraryPath(), removeLibraryPath(), and QLibrary.
void QApplication::setMainWidget ( QWidget * mainWidget )[virtual] β sets the application's main widget to mainWidget. She's the main character π
In most respects the main widget is just like any other widget, except that if it's closed, the application exits. Note that QApplication does not take ownership of the mainWidget, so if you create your main widget on the heap you must delete it yourself. No free cleanup, bestie π
You don't even need a main widget β connecting lastWindowClosed() to quit() is an alternative.
For X11, this function also resizes and moves the main widget according to the -geometry command-line option, so you should set the default geometry (using QWidget::setGeometry()) before calling setMainWidget().
See also mainWidget(), exec(), and quit().
Examples:
void QApplication::setOverrideCursor ( const QCursor & cursor, bool replace = FALSE )[static] β sets the application override cursor to cursor π±οΈβ¨
Application override cursors are intended for showing the user that the application is in a special state, like during an operation that might take some time. It's giving "hold on, working on it" energy.
This cursor will be displayed in all the application's widgets until restoreOverrideCursor() or another setOverrideCursor() is called.
Application cursors are stored on an internal stack. setOverrideCursor() pushes the cursor onto the stack, and restoreOverrideCursor() pops the active cursor off the stack. Every setOverrideCursor() must eventually be followed by a corresponding restoreOverrideCursor(), otherwise the stack will never be emptied. Unbalanced pushes? Not the vibe π
If replace is TRUE, the new cursor will replace the last override cursor (the stack keeps its depth). If replace is FALSE, the new stack is pushed onto the top of the stack.
Example:
QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
calculateHugeMandelbrot(); // lunch time...
QApplication::restoreOverrideCursor();
See also overrideCursor(), restoreOverrideCursor(), and QWidget::cursor.
Examples:
void QApplication::setPalette ( const QPalette & palette, bool informWidgets = FALSE, const char * className = 0 )[static] β changes the default application palette to palette π¨
If informWidgets is TRUE, then existing widgets are informed about the change and may adjust themselves to the new application setting. If informWidgets is FALSE, the change only affects newly created widgets. Fresh widgets only, iykyk.
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().
See also QWidget::palette, palette(), and QStyle::polish().
Examples:
void QApplication::setReverseLayout ( bool b )[static] β if b isTRUE, all dialogs and widgets will be laid out in a mirrored fashion, as required by right to left languages such as Arabic and Hebrew π If b isFALSE, dialogs and widgets are laid out left to right.
Changing this flag in runtime does not cause a relayout of already instantiated widgets. No take-backs, bestie π
See also reverseLayout().
void QApplication::setStartDragDistance ( int l )[static] β sets the distance after which a drag should start to l pixels.
See also startDragDistance().
void QApplication::setStartDragTime ( int ms )[static] β sets the time after which a drag should start to ms ms β±οΈ
See also startDragTime().
void QApplication::setStyle ( QStyle * style )[static] β 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. She takes the style object and raises it as her own, periodt.
Example usage:
QApplication::setStyle( new QWindowsStyle );
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.
See also style(), QStyle, setPalette(), and desktopSettingsAware().
Example: themes/themes.cpp.
QStyle * QApplication::setStyle ( const QString & style )[static] β this is an overloaded member function, provided for convenience π«Ά It behaves essentially like the above function.
Requests a QStyle object for style from the QStyleFactory.
The string must be one of the QStyleFactory::keys(), typically one of "windows", "motif", "cde", "motifplus", "platinum", "sgi" and "compact". Depending on the platform, "windowsxp", "aqua" or "macintosh" may be available.
A later call to the QApplication constructor will override the requested style when a -style option is passed in as a commandline parameter.
Returns 0 if an unknown style is passed, otherwise the QStyle object returned is set as the application's GUI style.
void QApplication::setWheelScrollLines ( int n )[static] β sets the number of lines to scroll when the mouse wheel is rotated to n π±οΈ
If this number exceeds the number of visible lines in a certain widget, the widget should interpret the scroll operation as a single page up / page down operation instead. Glow up scroll behaviour β¨
See also wheelScrollLines().
void QApplication::setWinStyleHighlightColor ( const QColor & c )[static] β this function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. π©
Sets the color used to mark selections in windows style for all widgets in the application. Will repaint all widgets if the color is changed.
The default color is darkBlue.
See also winStyleHighlightColor().
int QApplication::startDragDistance ()[static] β if you support drag and drop in your application and a drag should start after a mouse click and after moving the mouse a certain distance, you should use the value which this method returns as the distance.
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 currPos, you can find out if a drag should be started with code like this:
if ( ( startPos - currPos ).manhattanLength() >
QApplication::startDragDistance() )
startTheDrag();
Qt uses this value internally, e.g. in QFileDialog.
The default value is 4 pixels.
See also setStartDragDistance(), startDragTime(), and QPoint::manhattanLength().
int QApplication::startDragTime ()[static] β if you support drag and drop in your application and a drag should start after a mouse click and after a certain time elapsed, you should use the value which this method returns as the delay (in ms) β±οΈ
Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for starting a drag.
The default value is 500 ms.
See also setStartDragTime() and startDragDistance().
bool QApplication::startingUp ()[static] β returnsTRUEif an application object has not been created yet; otherwise returnsFALSE. Baby's first moments fr π£
See also closingDown().
QStyle & QApplication::style ()[static] β returns the application's style object. The look, the aesthetic, the whole lewk π
See also setStyle() and QStyle.
void QApplication::syncX ()[static] β synchronizes with the X server in the X11 implementation. This normally takes some time. Does nothing on other platforms.
See also flushX().
QWidgetList * QApplication::topLevelWidgets ()[static] β returns a list of the top level widgets in the application. π
The list is created using new and must be deleted by the caller. Yes bestie, that's on you.
The list is empty (QPtrList::isEmpty()) if there are no top level widgets.
Note that some of the top level widgets may be hidden, for example the tooltip if no tooltip is currently shown.
Example:
// Show all hidden top level widgets.
QWidgetList *list = QApplication::topLevelWidgets();
QWidgetListIt it( *list ); // iterate over the widgets
QWidget * w;
while ( (w=it.current()) != 0 ) { // for each top level widget...
++it;
if ( !w->isVisible() )
w->show();
}
delete list; // delete the list, not the widgets
Warning: Delete the list as soon you have finished using it. The widgets in the list may be deleted by someone else at any time. β οΈ Do not get caught slipping.
See also allWidgets(), QWidget::isTopLevel, QWidget::visible, and QPtrList::isEmpty().
QString QApplication::translate ( const char * context, const char * sourceText, const char * comment = 0, Encoding encoding = DefaultCodec ) constβ Note: This function is reentrant when Qt is built with thread support.
Returns the translation text for sourceText, by querying the installed messages files. The message files are searched from the most recently installed message file back to the first installed message file. Newest first, slay β¨
QObject::tr() and QObject::trUtf8() provide this functionality more conveniently.
context is typically a class name (e.g., "MyDialog") and sourceText is either English text or a short identifying text, if the output text will be very long (as for help texts).
comment is a disambiguating comment, for when the same sourceText is used in different roles within the same context. By default, it is null. encoding indicates the 8-bit encoding of character stings.
See the QTranslator documentation for more information about contexts and comments.
If none of the message files contain a translation for sourceText in context, this function returns a QString equivalent of sourceText. The encoding of sourceText is specified by encoding; it defaults to DefaultCodec.
This function is not virtual. You can use alternative translation techniques by subclassing QTranslator.
Warning: This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will most likely result in crashes or other undesirable behavior. π Please do not do this, bestie.
See also QObject::tr(), installTranslator(), and defaultCodec().
bool QApplication::tryLock ()
Okay so this one's the impatient sibling of lock() π
β it tries to grab the Qt Library Mutex and comes back immediately, no waiting around, no standing in line, no "give me one sec."
- If it got the lock? It returns
TRUE. Slay. π - If another thread already has the mutex? It returns
FALSEinstead of sitting there waiting for the lock to free up. She said "not today" and moved on.
Heads up bestie: the mutex must be unlocked with unlock() before another thread can successfully lock it. No sneaky shared custody. π
See also lock(), unlock(), and Thread Support in Qt.
Type QApplication::type () const
Returns the type of application β and your options are Tty, GuiClient, or GuiServer. That's the whole vibe check, no more, no less. πΈ
void QApplication::unlock ( bool wakeUpGui = TRUE )
Unlocks the Qt Library Mutex. β¨ And if wakeUpGui is TRUE (which it is by default, so yes, that's the normal path), the GUI thread gets woken up with QApplication::wakeUpGuiThread(). It's giving "hey girl, you're up" βοΈ
See also lock(), locked(), and Thread Support in Qt.
void QApplication::wakeUpGuiThread ()
Literally just wakes up the GUI thread. That's it. That's the function. Rip Van Winkle but make it Qt. π΄β‘οΈπ
See also guiThreadAwake() and Thread Support in Qt.
int QApplication::wheelScrollLines () [static]
Returns the number of lines to scroll when the mouse wheel is rotated. Yes, there's a whole setting for how much your wheel moves the page β she's got opinions about scroll distance. π±οΈ
See also setWheelScrollLines().
QWidget * QApplication::widgetAt ( int x, int y, bool child = FALSE ) [static]
Hands you a pointer to the widget sitting at global screen position (x, y), or 0 if there is no Qt widget hanging out there. Empty spot = nothing, bestie. π³οΈ
Here's the tea on child:
- If
childisFALSEand there is a child widget at (x, y), you get back the top-level widget containing it. (Going up the family tree. π³) - If
childisTRUE, you get the child widget at (x, y) itself.
Ngl this function is normally rather slow. Don't be calling it in a hot loop, she's not built for speed. π
See also QCursor::pos(), QWidget::grabMouse(), and QWidget::grabKeyboard().
QWidget * QApplication::widgetAt ( const QPoint & pos, bool child = FALSE ) [static]
This is an overloaded member function, provided for convenience. It behaves essentially like the above function. π«Ά
Returns a pointer to the widget at global screen position pos, or 0 if there is no Qt widget there.
- If
childisFALSEand there's a child widget at pos, the top-level widget containing it comes back. - If
childisTRUE, the child widget at pos comes back.
Same deal, just with a QPoint instead of two ints. Iconic. π
bool QApplication::winEventFilter ( MSG * ) [virtual]
This virtual function is only implemented under Windows. πͺ
The message procedure calls this function for every message received. Reimplement it if you want to process window messages that Qt doesn't process itself. And the vibe check on the return value:
- Return
TRUEif you don't want the event processed by Qt. - Otherwise return
FALSE.
void QApplication::winFocus ( QWidget * widget, bool gotFocus )
This function is available only on Windows. πͺ
- If
gotFocusisTRUE, widget will become the active window. π - Otherwise the active window is reset to
NULL.
const QColor & QApplication::winStyleHighlightColor () [static]
π¨ This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. Like, please, for your own good. π
Returns the color used to mark selections in windows style.
See also setWinStyleHighlightColor().
bool QApplication::x11EventFilter ( XEvent * ) [virtual]
This virtual function is only implemented under X11. π₯οΈ
If you create an application that inherits QApplication and reimplement this function, you get direct access to all X events that are received from the X server. Full backstage pass. ποΈ
Return value tea:
- Return
TRUEif you want to stop the event from being processed. - Return
FALSEfor normal event dispatching.
See also x11ProcessEvent().
int QApplication::x11ProcessEvent ( XEvent * event )
This function does the core processing of individual X events β normally by dispatching Qt events to the right destination. She's the dispatcher, the air traffic controller, the group chat admin. π¬
Returns:
1if the event was consumed by special handling0if the event was consumed by normal handling-1if the event was for an unrecognized widget π
See also x11EventFilter().
π RELATED FUNCTION DOCUMENTATION π
void Q_ASSERT ( bool test )
Prints a warning message containing the source code file name and line number if test is FALSE. She's tattling, but helpfully. π£οΈ
This is really a macro defined in qglobal.h.
Q_ASSERT is useful for testing pre- and post-conditions.
Example:
//
// File: div.cpp
//
#include <qglobal.h>
int divide( int a, int b )
{
Q_ASSERT( b != 0 ); // this is line 9
return a/b;
}
If b is zero, the Q_ASSERT statement will output the following message using the qWarning() function:
ASSERT: "b != 0" in div.cpp (9)
See also qWarning() and Debugging.
void Q_CHECK_PTR ( void * p )
If p is 0, prints a warning message containing the source code file name and line number, saying that the program ran out of memory. π§ π₯
This is really a macro defined in qglobal.h.
Example:
int *a;
Q_CHECK_PTR( a = new int[80] ); // WRONG!
a = new (nothrow) int[80]; // Right
Q_CHECK_PTR( a );
See also qWarning() and Debugging.
void qAddPostRoutine ( QtCleanUpFunction p )
Adds a global routine that will be called from the QApplication destructor. This function is normally used to add cleanup routines for program-wide functionality. π§Ήβ¨
The function given by p should take no arguments and return nothing, like this:
static int *global_ptr = 0;
static void cleanup_ptr()
{
delete [] global_ptr;
global_ptr = 0;
}
void init_ptr()
{
global_ptr = new int[100]; // allocate data
qAddPostRoutine( cleanup_ptr ); // delete later
}
Not me about to warn you: for an application- or module-wide cleanup,qAddPostRoutine()is often not suitable. People have a tendency to make such modules dynamically loaded, and then unload those modules long before theQApplicationdestructor is called, for example. π
For modules and libraries, using a reference-counted initialization manager or Qt's parent-child delete mechanism may be better. Here is an example of a private class which uses the parent-child mechanism to call a cleanup function at the right time:
class MyPrivateInitStuff: public QObject {
private:
MyPrivateInitStuff( QObject * parent ): QObject( parent) {
// initialization goes here
}
MyPrivateInitStuff * p;
public:
static MyPrivateInitStuff * initStuff( QObject * parent ) {
if ( !p )
p = new MyPrivateInitStuff( parent );
return p;
}
~MyPrivateInitStuff() {
// cleanup (the "post routine") goes here
}
}
By selecting the right parent widget/object, this can often be made to clean up the module's data at the exact right moment. Timing is everything, bestie. β°
void qDebug ( const char * msg, ... )
Prints a debug message msg, or calls the message handler (if it has been installed). π
This function takes a format string and a list of arguments, similar to the C printf() function.
Example:
qDebug( "my window handle = %x", myWidget->id() );
Under X11, the text is printed to stderr. Under Windows, the text is sent to the debugger.
β οΈ Warning: The internal buffer is limited to 8196 bytes (including the '\0'-terminator).
β οΈ Warning: Passing(const char *)0as argument toqDebugmight lead to crashes on certain platforms due to the platformsprintfimplementation. Do not do this. Please. π
See also qWarning(), qFatal(), qInstallMsgHandler(), and Debugging.
void qFatal ( const char * msg, ... )
Prints a fatal error message msg and exits, or calls the message handler (if it has been installed). This one is the dramatic exit. π
This function takes a format string and a list of arguments, similar to the C printf() function.
Example:
int divide( int a, int b )
{
if ( b == 0 ) // program error
qFatal( "divide: cannot divide by zero" );
return a/b;
}
Under X11, the text is printed to stderr. Under Windows, the text is sent to the debugger.
β οΈ Warning: The internal buffer is limited to 8196 bytes (including the '\0'-terminator).
β οΈ Warning: Passing(const char *)0as argument toqFatalmight lead to crashes on certain platforms due to the platformsprintfimplementation.
See also qDebug(), qWarning(), qInstallMsgHandler(), and Debugging.
QtMsgHandler qInstallMsgHandler ( QtMsgHandler h )
Installs a Qt message handler h. Returns a pointer to the message handler previously defined. π
The message handler is a function that prints out debug messages, warnings and fatal error messages. The Qt library (debug version) contains hundreds of warning messages that are printed when internal errors (usually invalid function arguments) occur. If you implement your own message handler, you get total control of these messages. Main character energy, honestly. π
The default message handler prints the message to the standard output under X11 or to the debugger under Windows. If it is a fatal message, the application aborts immediately.
Only one message handler can be defined, since this is usually done on an application-wide basis to control debug output. No polyamory here. π
To restore the message handler, call qInstallMsgHandler(0).
Example:
#include <qapplication.h>
#include <stdio.h>
#include <stdlib.h>
void myMessageOutput( QtMsgType type, const char *msg )
{
switch ( type ) {
case QtDebugMsg:
fprintf( stderr, "Debug: %s\n", msg );
break;
case QtWarningMsg:
fprintf( stderr, "Warning: %s\n", msg );
break;
case QtFatalMsg:
fprintf( stderr, "Fatal: %s\n", msg );
abort(); // deliberately core dump
}
}
int main( int argc, char **argv )
{
qInstallMsgHandler( myMessageOutput );
QApplication a( argc, argv );
...
return a.exec();
}
See also qDebug(), qWarning(), qFatal(), and Debugging.
bool qSysInfo ( int * wordSize, bool * bigEndian )
Obtains information about the system. π
The system's word size in bits (typically 32) is returned in *wordSize. The *bigEndian is set to TRUE if this is a big-endian machine, or to FALSE if this is a little-endian machine.
In debug mode, this function calls qFatal() with a message if the computer is truly weird (i.e. different endianness for 16 bit and 32 bit integers); in release mode it returns FALSE. Weird computer behavior is not tolerated. π€
void qSystemWarning ( const char * msg, int code )
Prints the message msg and uses code to get a system specific error message. When code is -1 (the default), the system's last error code will be used if possible. Use this method to handle failures in platform specific API calls. π οΈ
This function does nothing when Qt is built with QT_NO_DEBUG defined.
const char * qVersion ()
okay bestie, so qVersion() is literally the vibe check for your Qt version β it returns the version number as a string, like "2.3.0" or "3.0.5" β¨. and the QT_VERSION define? it's numeric, in the form 0xmmiibb where m = major, i = minor, b = bugfix. so for Qt 3.0.5, QT_VERSION is 0x030005. no cap. π
void qWarning ( const char * msg, ... )
qWarning() prints a warning message msg, or calls the message handler if one has been installed. it takes a format string and a list of arguments, just like C's printf(). π«Ά
example:
void f( int c )
{
if ( c > 200 )
qWarning( "f: bad argument, c == %d", c );
}
under X11, the text is printed to stderr. under Windows, the text is sent to the debugger. π
warning: the internal buffer is limited to 8196 bytes (including the '\0'-terminator). so don't go overboard, bestie.
warning: passing(const char *)0as an argument toqWarningmight lead to crashes on certain platforms due to the platform'sprintfimplementation. so like, just don't. π
see also qDebug(), qFatal(), qInstallMsgHandler(), and Debugging.
SEE ALSO π
COPYRIGHT π
Copyright 1992-2007 Trolltech ASA, http://www.trolltech.com. See the license file included in the distribution for a complete license statement.
AUTHOR βοΈ
Generated automatically from the source code.
BUGS π
if you find a bug in Qt, please report it as described in http://doc.trolltech.com/bughowto.html. good bug reports help us to help you. thank you! π«Ά
the definitive Qt documentation is provided in HTML format; it's located at $QTDIR/doc/html and can be read using Qt Assistant or with a web browser. this man page is provided as a convenience for those users who prefer man pages, although this format is not officially supported by Trolltech. πββοΈ
if you find errors in this manual page, please report them to qt-bugs@trolltech.com. please include the name of the manual page (qapplication.3qt) and the Qt version (3.3.8). ty bestie! π
and that's a wrap! this iconic page was brought to you by Trolltech AS on 2 February 2007 for QApplication(3qt). stay slay, and may your warnings always be caught. π β¨
π¦ where this page comes from
- fedora 43: qt3-devel-docs 3.3.8b-102.fc43 Β· QPL-1.0 OR GPL-2.0-only OR GPL-3.0-only
- fedora 44: qt3-devel-docs 3.3.8b-103.fc44 Β· QPL-1.0 OR GPL-2.0-only OR GPL-3.0-only
- Copyright 1992-2007 Trolltech ASA. All rights reserved. See the
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms