HomeHome

Classes - Annotated - Tree - Functions - Home - Structure Qte

QApplication Class Reference


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

#include <qapplication.h>

Inherits QObject.

Inherited by QXtApplication.

List of all member functions.

Public Members

Public Slots

Signals

Static Public Members

Related Functions

(Note that these are not member functions.)

Detailed Description

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

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 initialization and finalization, and provides session management. Finally, it handles most system-wide and application-wide settings.

For any GUI application that uses Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or even more windows at the moment.

This object (you can access is using the global variable qApp) does a great many things, most importantly:

The Application walk-through example contains a typical complete main() that does the usual things with QApplication.

Since the QApplication object does so much initialization, it is absolutely necessary to create it before any other objects related to the user interface are created.

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

Groups of functions:

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.

Examples: xml/tagreader-with-features/tagreader.cpp listbox/main.cpp forever/forever.cpp layout/layout.cpp splitter/splitter.cpp hello/main.cpp rangecontrols/main.cpp addressbook/main.cpp customlayout/main.cpp progress/progress.cpp aclock/main.cpp wizard/main.cpp rot13/rot13.cpp iconview/main.cpp popup/popup.cpp listboxcombo/main.cpp checklists/main.cpp tictac/main.cpp dclock/main.cpp application/main.cpp lineedits/main.cpp movies/main.cpp picture/picture.cpp mdi/main.cpp biff/main.cpp showimg/main.cpp qfd/qfd.cpp fileiconview/main.cpp xform/xform.cpp tabdialog/main.cpp life/main.cpp themes/main.cpp i18n/main.cpp menu/menu.cpp richtext/main.cpp drawlines/connect.cpp scribble/main.cpp qmag/qmag.cpp dirview/main.cpp cursor/cursor.cpp action/main.cpp buttongroups/main.cpp helpviewer/main.cpp qwerty/main.cpp validator/main.cpp desktop/desktop.cpp scrollview/scrollview.cpp listviews/main.cpp drawdemo/drawdemo.cpp tooltip/main.cpp progressbar/main.cpp


Member Function Documentation

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

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

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 (includes widgets, pixmaps, bitmaps etc.)

Notice that argc and argv might be changed. Qt removes command line arguments that it recognizes. The original argc and argv are can be accessed later by qApp->argc() and qApp->argv(). The documentation for argv() contains a detailed description of how to process command line arguments.

Qt debugging options (not available if Qt was compiled with the NO_DEBUG flag defined):

See Debugging Techniques for a more detailed explanation.

All Qt programs automatically support the following command line options:

The X11 version of Qt also supports some traditional X11 command line options:

See also argc() and argv().

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

For Qt/Embedded, passing QApplication::GuiServer for type make this application the server (equivalent to running with the -qws option).

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

Constructs an application object with the command line arguments argc and argv. If GUIenabled is TRUE, a normal application is constructed, otherwise a non-GUI application is created.

Set GUIenabled to FALSE for programs without a graphical user interface that should be able to run without a window system.

On X11, the window system is initialized if GUIenabled is TRUE. If GUIenabled is FALSE, the application does not connect to the X-server.

On Windows, currently the window system is always initialized, regardless of the value of GUIenabled. This may change in future versions of Qt.

The following example shows how to create an application that uses a graphical interface when available.

  int main( int argc, char **argv )
  {
    QApplication app(argc, argv, useGUI);

    if ( useGUI ) {
       //start GUI version
       ...
    } else {
       //start non-GUI version
       ...
    }
    return app.exec();
  }

QApplication::~QApplication () [virtual]

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

void QApplication::aboutToQuit () [signal]

This signal is emitted when the application is about to quit the main event loop. This may happen either after a call to quit() from inside the application or when the users shuts down the entire desktop session.

The signal is particularly useful if your application has to do some last-second cleanups. Note that no user interaction is possible at this state.

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 to TRUE. A modal widget must be finished before the user can continue with other parts of the program.

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

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.

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 on top of the stack.

See also activeModalWidget() and topLevelWidgets().

QWidget * QApplication::activeWindow () const

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

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

QWidgetList * QApplication::allWidgets () [static]

Returns a list of all the widgets in the application.

The list is created using new and must be deleted by the caller.

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

Note that some of the widgets may be hidden.

Example:

    //
    // 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 away as soon you have finished using it. The widgets in the list may be deleted by someone else at any time.

See also topLevelWidgets(), QWidget::isVisible() and QList::isEmpty(),.

int QApplication::argc () const

Returns the number of command line arguments.

The documentation for argv() contains a detailed description of how to process command line arguments.

See also argv() and QApplication::QApplication().

char ** QApplication::argv () const

Returns the command line argument vector.

argv()[0] is the program name, argv()[1] is the first argument and argv()[argc()-1] is the last argument.

A QApplication object is constructed by passing argc and argv from the main() function. Some of the arguments may be recognized as Qt options removed from the argument vector. For example, the X11 version of Qt knows about -display, -font and a few more options.

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

See also argc() and QApplication::QApplication().

void QApplication::beep () [static]

Sounds the bell, using the default volume and sound.

QClipboard * QApplication::clipboard () [static]

Returns a pointer to the application global clipboard.

void QApplication::closeAllWindows () [slot]

A convenience function that closes all toplevel windows.

The function is particularly useful for applications with many toplevel 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( tr("&Quit"), qApp, SLOT(closeAllWindows()), CTRL+Key_Q );

    // when the last window was 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.

See also QWidget::close(), QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets() and QWidget::isTopLevel().

bool QApplication::closingDown () [static]

Returns TRUE if the application objects are being destroyed.

See also startingUp().

int QApplication::colorSpec () [static]

Returns the color specification.

See also QApplication::setColorSpec().

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.

Usually this means saving of all open files, after getting permission from the user. Furthermore you may want to provide the user a way to cancel the shutdown.

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.

Important
Within this function, no user interaction is possible, unless you ask the session manager sm for explicit permission. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details and example usage.

The default implementation requests interaction and sends a close event to all visible toplevel widgets. If at least one event was rejected, the shutdown is cancelled.

See also isSessionRestored(), sessionId() and saveState().

int QApplication::cursorFlashTime () [static]

Returns the text cursor's flash time in milliseconds. The flash time is the time required to display, invert and restore the caret display.

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 vary any time the user changes the global desktop settings.

See also setCursorFlashTime().

QTextCodecQApplication::defaultCodec () const

Returns the default codec (see setDefaultCodec()). Returns 0 by default (no codec).

QWidget * QApplication::desktop () [static]

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

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, as it works on some machines and not on others.

    QWidget *d = QApplication::desktop();
    int w=d->width();                   // returns screen width
    int h=d->height();                  // returns screen height

Examples: scribble/main.cpp qmag/qmag.cpp helpviewer/main.cpp

bool QApplication::desktopSettingsAware () [static]

Returns the value set by setDesktopSettingsAware(), by default TRUE.

See also setDesktopSettingsAware().

int QApplication::doubleClickInterval () [static]

Returns the maximum duration for a double click.

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 enters the main event loop (recursively). Do not call it unless you really know what you are doing.

See also exit_loop() and loopLevel().

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 via 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 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 by using processEvents() and processOneEvent().

See also quit(), exit(), processEvents() and setMainWidget().

Examples: xml/tagreader-with-features/tagreader.cpp listbox/main.cpp forever/forever.cpp layout/layout.cpp splitter/splitter.cpp hello/main.cpp rangecontrols/main.cpp addressbook/main.cpp customlayout/main.cpp progress/progress.cpp mainlyQt/editor.cpp aclock/main.cpp rot13/rot13.cpp iconview/main.cpp popup/popup.cpp listboxcombo/main.cpp checklists/main.cpp tictac/main.cpp dclock/main.cpp application/main.cpp lineedits/main.cpp movies/main.cpp picture/picture.cpp mdi/main.cpp biff/main.cpp showimg/main.cpp qfd/qfd.cpp fileiconview/main.cpp xform/xform.cpp tabdialog/main.cpp life/main.cpp themes/main.cpp i18n/main.cpp menu/menu.cpp richtext/main.cpp drawlines/connect.cpp scribble/main.cpp qmag/qmag.cpp dirview/main.cpp cursor/cursor.cpp action/main.cpp buttongroups/main.cpp helpviewer/main.cpp qwerty/main.cpp validator/main.cpp scrollview/scrollview.cpp listviews/main.cpp drawdemo/drawdemo.cpp tooltip/main.cpp progressbar/main.cpp

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, retcode 0 means success, any non-zero value indicates an error.

Note that unlike the C library function of the same name, this function does returns to the caller - it is event processing that stops.

See also quit() and exec().

Examples: picture/picture.cpp

void QApplication::exit_loop ()

This function leaves from a recursive call to the main event loop. Do not call it unless you are an expert.

See also enter_loop() and loopLevel().

void QApplication::flushX () [static]

Flushes the X event queue in the X11 implementation. This normally returns almost immediately. Does nothing on other platforms.

See also syncX().

QWidget * QApplication::focusWidget () const

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

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

QFont QApplication::font ( const QWidget * w = 0 ) [static]

Returns the default font for a widget. Basically this function uses w->className() to get a font for it.

If w is 0 the default application font is returned.

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

QFontMetrics QApplication::fontMetrics () [static]

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

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

QSize QApplication::globalStrut () [static]

Returns the global strut of the application.

See also setGlobalStrut().

void QApplication::guiThreadAwake () [signal]

This signal is emitted when the GUI threads is about to process a cycle of the event loop.

See also wakeUpGuiThread().

bool QApplication::hasGlobalMouseTracking () [static]

Returns TRUE if global mouse tracking is enabled, otherwise FALSE.

See also setGlobalMouseTracking().

void QApplication::installTranslator ( QTranslator * mf )

Adds mf to the list of message files to be used for localization. Message files are searched starting with the most recently added file.

See also removeTranslator(), translate() and QObject::tr().

bool QApplication::isEffectEnabled ( Qt::UIEffect effect ) [static]

Returns TRUE if effect is enabled, otherwise FALSE.

By default, Qt will try to use the desktop settings, and setDesktopSettingsAware() must be called to prevent this.

sa\ setEffectEnabled(), Qt::UIEffect.

bool QApplication::isSessionRestored () const

Returns whether the application has been restored from an earlier session.

See also sessionId(), commitData() and saveState().

void QApplication::lastWindowClosed () [signal]

This signal is emitted when the user has closed the last remaining 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, transient toplevel widgets such as popup menus and dialogs are omitted.

See also mainWidget(), topLevelWidgets(), QWidget::isTopLevel() and QWidget::close().

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

bool QApplication::locked ()

Returns TRUE if the Qt library mutex is locked by a different thread, otherwise returns FALSE.

NOTE: Due to differing implementations of recursive mutexes on various platforms, calling this function from the same thread that previous locked the mutex will return undefined results.

See also lock() and unlock().

int QApplication::loopLevel () const

Returns the current loop level

See also enter_loop() and exit_loop().

QWidget * QApplication::mainWidget () const

Returns the main application widget, or a null pointer if there is not a defined main widget.

See also setMainWidget().

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

Sends event to receiver: receiver->event( event ) Returns the value that is returned from the receiver's event handler.

Reimplementing this virtual function is one of five ways to process an event:

  1. Reimplementing this function. Very powerful, you get complete control, but of course only one subclass can be qApp.
  2. Installing an event filter on qApp. Such an event filter gets to process all events for all widgets, so it's just as powerful as reimplementing notify(), and in this way it's possible to have more than one application-global event filter. Global event filter get to see even mouse events for disabled widgets, and if global mouse tracking is enabled, mouse move events for all widgets.
  3. Reimplementing QObject::event() (as QWidget does). If you do this you get tab key-presses, and you get to see the events before any widget-specific event filters.
  4. Installing an event filter on the object. Such an even filter gets all the events except Tab and Shift-Tab key presses.
  5. Finally, reimplementing paintEvent(), mousePressEvent() and so on. This is the normal, 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 a pointer to the default application palette. There is always an application palette, i.e. the returned pointer is guaranteed to be non-null.

If a widget is passed as argument, the default palette for the widget's class is returned. This may or may not be the application palett. In most cases there isn't be 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().

void QApplication::polish ( QWidget * w ) [virtual]

Polishing of widgets.

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 public functions of QWidget. Instead, based on meta information like QObject::className() you are able to customize any kind of widgets.

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

void QApplication::postEvent ( QObject * receiver, QEvent * event ) [static]

Stores the event in a queue and returns immediately.

The event must be allocated on the heap, as it is deleted when the event 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().

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 doing a long operation (e.g. copying a file).

See also processOneEvent(), exec() and QTimer.

void QApplication::processEvents ( int maxtime )

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 processOneEvent(), exec() and QTimer.

void QApplication::processOneEvent ()

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

This function is a slot, so you may connect any signal to activate quit().

Example:

    QPushButton *quitButton = new QPushButton( "Quit" );
    connect( quitButton, SIGNAL(clicked()), qApp, SLOT(quit()) );

See also exit() and aboutToQuit().

void QApplication::removePostedEvents ( QObject * receiver ) [static]

Removes all events posted using postEvent() for receiver.

The events are not dispatched, simply 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 )

Removes mf from the list of message files used by this application. Does not, of course, delete mf.

See also installTranslator(), translate() and QObject::tr().

void QApplication::restoreOverrideCursor () [static]

Undoes the last setOverrideCursor().

If setOverrideCursor() has been called twice, calling restoreOverrideCursor() will activate the first cursor set. Calling this function a second time restores the original widgets cursors.

See also setOverrideCursor() and overrideCursor().

void QApplication::saveState ( QSessionManager & sm ) [virtual]

This function deals with session management. It is invoked when the session manager wants the application to preserve its state for a future session.

For a text editor this would mean creating a temporary file that includes the current contents of the edit buffers, the location of the cursor and other aspects of the current editing session.

Note that you should never exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context. Futhermore, 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.

Important
Within this function, no user interaction is possible, unless you ask the session manager sm for explicit permission. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details.

See also isSessionRestored(), sessionId() and commitData().

bool QApplication::sendEvent ( QObject * receiver, QEvent * event ) [static]

Sends an event directly to a receiver, using the notify() function. Returns the value that was returned from the event handler.

See also postEvent() and notify().

Examples: popup/popup.cpp

void QApplication::sendPostedEvents () [static]

Dispatches all posted events.

void QApplication::sendPostedEvents ( QObject * receiver, int event_type ) [static]

Immediately dispatches all events which have been previously enqueued with QApplication::postEvent() and which are for the object receiver and have the event_type.

Some event compression may occur. Note that events from the window system are not dispatched by this function.

QString QApplication::sessionId () const

Returns the identifier of the current session.

If the application has been restored from an earlier session, this identifier is the same as it was in that previous session.

The session identifier is guaranteed to be unique for both different applications and different instances of the same application.

See also isSessionRestored(), commitData() and saveState().

void QApplication::setColorSpec ( int spec ) [static]

Sets the color specification for the application to spec.

The color specification controls how your application allocates colors when run on a display with a limited amount of colors, i.e. 8 bit / 256 color displays.

The color specification must be set before you create the QApplication object.

The choices are:

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

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 see what mode you end up with, you can call QColor::numBitPlanes() once the QApplication object exists. A value greater than 8 (typically 16, 24 or 32) means true color.

The color cube used by Qt are all those colors with red, green, and blue components of either 0x00, 0x33, 0x66, 0x99, 0xCC, or 0xFF.

See also colorSpec(), QColor::numBitPlanes() and QColor::enterAllocContext().

Examples: showimg/main.cpp themes/main.cpp tetrix/tetrix.cpp helpviewer/main.cpp

void QApplication::setCursorFlashTime ( int msecs ) [static]

Sets the text cursor's flash time to msecs milliseconds. The flash time is the time required to display, invert and restore the caret display: A full flash cycle. Usually, the text cursor is displayed for msecs/2 milliseconds, then hidden for msecs/2 milliseconds, but this may vary.

Note that on Microsoft Windows, calling this function sets the cursor flash time for all windows.

See also cursorFlashTime().

void QApplication::setDefaultCodec ( QTextCodec * codec )

If the literal quoted text in the program is not in the Latin1 encoding, this function can be used to set the appropriate encoding. For example, software developed by Korean programmers might use eucKR for all the text in the program, in which case main() would be:

    main(int argc, char** argv)
    {
        QApplication app(argc, argv);
        ... install any additional codecs ...
        app.setDefaultCodec( QTextCodec::codecForName("eucKR") );
        ...
    }

Note that this is not the way to select the encoding that the user has chosen. For example, to convert an application containing literal English strings to Korean, all that is needed is for the English strings to be passed through tr() and for translation files to be loaded. For details of internationalization, see the Qt Internationalization documentation.

Note also that some Qt built-in classes call tr() with various strings. These strings are in English, so for a full translation, a codec would be required for these strings.

void QApplication::setDesktopSettingsAware ( bool on ) [static]

By default, Qt will try to get the current standard colors, fonts etc. from the underlying window system's desktop settings (resources), and use them for all relevant widgets. This behavior can be switched off by calling this function with on set to FALSE.

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 );           // gimme 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.

Note that 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.

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 informWidgets is TRUE, then existing widgets are informed about the change and thus may adjust themselves to the new application setting. Otherwise the change only affects newly created widgets. 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 both with window system version and with locale. This function lets you override it. Note that overriding it may be a bad idea, for example some locales need extra-big fonts to support their special characters.

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

Examples: showimg/main.cpp qfd/qfd.cpp desktop/desktop.cpp

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. tool tips.

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

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

void QApplication::setGlobalStrut ( const QSize & strut ) [static]

Sets the application strut to strut. No GUI-element that can be interacted with should be smaller than the provided size. This should be considered when reimplementing items that may be used on touch-screens or with similar IO-devices.

Example:

  QSize& WidgetClass::sizeHint() const
  {
      return QSize( 80, 25 ).expandedTo( QApplication::globalStrut() );
  }

See also golbalStrut().

void QApplication::setMainWidget ( QWidget * mainWidget ) [virtual]

Sets the main widget of the application.

The main widget is like any other, in most respects except that if it is deleted, the application exits.

You need not have a main widget; connecting lastWindowClosed() to quit() is another 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: xml/tagreader-with-features/tagreader.cpp listbox/main.cpp forever/forever.cpp layout/layout.cpp splitter/splitter.cpp hello/main.cpp rangecontrols/main.cpp addressbook/main.cpp customlayout/main.cpp progress/progress.cpp mainlyQt/editor.cpp aclock/main.cpp rot13/rot13.cpp iconview/main.cpp popup/popup.cpp listboxcombo/main.cpp checklists/main.cpp tictac/main.cpp dclock/main.cpp lineedits/main.cpp picture/picture.cpp biff/main.cpp qfd/qfd.cpp fileiconview/main.cpp xform/xform.cpp tabdialog/main.cpp life/main.cpp themes/main.cpp i18n/main.cpp menu/menu.cpp richtext/main.cpp drawlines/connect.cpp scribble/main.cpp qmag/qmag.cpp dirview/main.cpp cursor/cursor.cpp buttongroups/main.cpp validator/main.cpp listviews/main.cpp drawdemo/drawdemo.cpp tooltip/main.cpp progressbar/main.cpp

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, for example during an operation that might take some time.

This cursor will be displayed in all the widgets of the application 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.

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( Qt::waitCursor );
    calculateHugeMandelbrot();                  // lunch time...
    QApplication::restoreOverrideCursor();

See also overrideCursor(), restoreOverrideCursor() and QWidget::setCursor().

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 thus may adjust themselves to the new application setting. Otherwise the change only affects newly created widgets. If className is passed, the change applies only to classes that inherit className (as reported by QObject::inherits()).

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

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

void QApplication::setStartDragDistance ( int l ) [static]

Sets the distance after which a drag should start.

See also startDragDistance().

void QApplication::setStartDragTime ( int ms ) [static]

Sets the time after which a drag should start.

See also startDragTime().

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

Sets the application 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.

Example usage:

    QApplication::setStyle( new QWindowStyle );

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

void QApplication::setWheelScrollLines ( int n ) [static]

Sets the number of lines to scroll when the mouse wheel is rotated.

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.

See also wheelScrollLines().

void QApplication::setWinStyleHighlightColor ( const QColor & c ) [static]

This function is obsolete. It is provided to keep old source working, and will probably be removed in a future version of Qt. 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'n'drop in you 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. So 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 a code like this:

  if ( ( startPos - currPos ).manhattanLength() > QApplication::startDragDistance() )
      startTheDrag();

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

The default value is set to 4 pixels.

See also setStartDragDistance(), startDragTime() and QPoint::manhattanLength().

int QApplication::startDragTime () [static]

If you support drag'n'drop in you 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 delay (in ms).

Qt internally uses also this delay e.g. in QMultiLineEdit for starting a drag.

The default value is set to 500 ms.

See also setStartDragTime() and startDragDistance().

bool QApplication::startingUp () [static]

Returns TRUE if an application object has not been created yet.

See also closingDown().

QStyleQApplication::style () [static]

Returns the style object of the application.

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.

The list is empty (QList::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:

    //
    // Shows 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 away as soon you have finished using it. The widgets in the list may be deleted by someone else at any time.

See also allWidgets(), QWidget::isTopLevel(), QWidget::isVisible() and QList::isEmpty().

QString QApplication::translate ( const char * scope, const char * key, const char * comment ) const

Returns the translation text for key, by querying the installed messages files. The message file that was installed last is asked first.

QObject::tr() offers a more convenient way to use this functionality.

scope is typically a class name (e.g. MyDialog) and key is either English text or a short marker text, if the output text will be very long (as for help texts).

comment is a disambiguating comment, for when the same text is used in different roles within one context.

See the QTranslator documentation for more information about keys, contexts and comments.

If none of the message files contain a translation for key in scope, this function returns key.

This function is not virtual, but you can add alternative translation techniques by installing subclasses of QTranslator.

See also QObject::tr(), installTranslator(), removeTranslator() and QTranslator.

QString QApplication::translate ( const char * context, const char * key ) const

This function is obsolete. It is provided to keep old source working, and will probably be removed in a future version of Qt. We strongly advise against using it in new code.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

This version of the function uses "" as comment.

void QApplication::unlock ( bool wakeUpGui = TRUE )

Unlock the Qt library mutex. if wakeUpGui is TRUE (default argument), then the GUI thread will be woken with QApplication::wakeUpGuiThread().

See also lock() and locked().

void QApplication::wakeUpGuiThread ()

Wakes up the GUI thread.

See also guiThreadAwake().

int QApplication::wheelScrollLines () [static]

Returns the number of lines to scroll when the mouse wheel is rotated.

See also setWheelScrollLines().

QWidget * QApplication::widgetAt ( int x, int y, bool child=FALSE ) [static]

Returns a pointer to the widget at global screen position (x,y), or a null pointer if there is no Qt widget there.

If child is FALSE and there is a child widget at position (x,y), the top-level widget containing it is returned. If child is TRUE the child widget at position (x,y) is returned.

This function is normally rather slow.

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 differs from the above function only in what argument(s) it accepts.

const QColorQApplication::winStyleHighlightColor () [static]

This function is obsolete. It is provided to keep old source working, and will probably be removed in a future version of Qt. We strongly advise against using it in new code.

Returns the color used to mark selections in windows style.

See also setWinStyleHighlightColor().


Related Functions

void qFatal (const char * msg, ...)

Prints a fatal error message and exits, 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:

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

See also qDebug(), qWarning(), qInstallMsgHandler() and Debugging

void qWarning (const char * msg, ...)

Prints a warning message, 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:

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

See also qDebug(), qFatal(), qInstallMsgHandler() and Debugging

Examples: progress/progress.cpp tictac/main.cpp life/main.cpp

const char * qVersion ()

Returns the Qt version number for the library, typically "1.30" or "2.1.0".

void qAddPostRoutine (Q_CleanUpFunction 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
    }

Note that 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 the QApplication destructor is called, for example.

For modules and libraries, using a reference-counted initialization manager or Qt' 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.

void ASSERT (bool test)

Prints a warning message containing the source code file name and line number if test is FALSE.

This is really a macro defined in qglobal.h.

ASSERT is useful for testing required conditions in your program.

Example:

    //
    // File: div.cpp
    //

    #include <qglobal.h>

    int divide( int a, int b )
    {
        ASSERT( b != 0 );                       // this is line 9
        return a/b;
    }

If b is zero, the ASSERT statement will output the following message using the qWarning() function:

    ASSERT: "b == 0" in div.cpp (9)

See also qWarning() and Debugging

void qDebug (const char * msg, ...)

Prints a debug message, 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).

See also qWarning(), qFatal(), qInstallMsgHandler() 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.

This function calls qFatal() with a message if the computer is truly weird (i.e. different endianness for 16 bit and 32 bit integers).

void CHECK_PTR (void * p)

If p is null, a fatal messages says that the program ran out of memory and exits. If p is not null, nothing happens.

This is really a macro defined in qglobal.h.

Example:

    int *a;
    CHECK_PTR( a = new int[80] );       // never do this!
      // do this instead:
    a = new int[80];
    CHECK_PTR( a );                     // this is fine

See also qFatal() and Debugging

msg_handler qInstallMsgHandler (msg_handler h)

Installs a Qt message handler. 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.

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.

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();                        // dump core on purpose
        }
    }

    int main( int argc, char **argv )
    {
        qInstallMsgHandler( myMessageOutput );
        QApplication a( argc, argv );
        ...
        return a.exec();
    }

See also qDebug(), qWarning(), qFatal() and Debugging


Search the documentation, FAQ, qt-interest archive and more (uses www.trolltech.com):


This file is part of the Qt toolkit, copyright © 1995-2005 Trolltech, all rights reserved.


Copyright © 2005 TrolltechTrademarks
Qt version 2.3.10