Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |
The QApplication class manages the GUI application's control flow and main settings. More...
#include <qapplication.h>
Inherits QObject.
Inherited by QXtApplication.
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.
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.
The QApplication object is accessible through the global variable qApp. Its main areas of responsibility are:
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 must be created 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.)
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.
See also Main Window and Related Classes.
See setColorSpec() for full details.
This enum type defines the 8-bit encoding of character string arguments to translate():
See also QObject::tr(), QObject::trUtf8() and QString::fromUtf8().
The global qApp pointer refers to this application object. Only one application object should be created.
This application object must be constructed before any paint devices (including widgets, pixmaps, bitmaps etc.).
Note that argc and argv might be changed. Qt removes command line arguments that it recognizes. The original argc and argv can be accessed later with 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 QT_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:
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 and Macintosh, currently the window system is always initialized, regardless of the value of GUIenabled. This may change in future versions of Qt.
For threaded configurations (i.e. when Qt has been built as a threaded library), the application global mutex will be locked in the constructor and unlocked when entering the event loop with exec(). You must unlock the mutex explicitly if you don't call exec(), otherwise you might get warnings on application exit.
The following example shows 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(); }
For Qt/Embedded, passing QApplication::GuiServer for type makes this application the server (equivalent to running with the -qws option).
This is available only on X11.
This is available only on X11.
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 cleanup. Note that no user interaction is possible in this state.
See also quit().
A modal widget is a special top level widget which is a subclass of QDialog that specifies the modal parameter of the constructor as TRUE. A modal widget must be closed before the user can continue with other parts of the program.
Modal widgets are organized in a stack. This function returns the active modal widget at the top of the stack.
See also activePopupWidget() and topLevelWidgets().
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 at the top of the stack.
See also activeModalWidget() and topLevelWidgets().
Returns the application top-level window that has the keyboard input focus, or 0 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::focus and focusWidget().
Example: network/mail/smtp.cpp.
See also removeLibraryPath(), libraryPaths() and setLibraryPaths().
The list is created using new and must be deleted by the caller.
The list is empty (QPtrList::isEmpty()) if there are no widgets.
Note that some of the widgets may be hidden.
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().
Returns the number of command line arguments.
The documentation for argv() describes how to process command line arguments.
See also argv() and QApplication::QApplication().
Example: scribble/scribble.cpp.
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 and 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().
Example: scribble/scribble.cpp.
Example: showimg/showimg.cpp.
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.
See also QWidget::close(), QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets() and QWidget::isTopLevel.
Examples: action/application.cpp, application/application.cpp, helpviewer/helpwindow.cpp, mdi/application.cpp and qwerty/qwerty.cpp.
See also startingUp().
See also QApplication::setColorSpec().
Example: showimg/showimg.cpp.
This function deals with session management. It is invoked when the QSessionManager wants the application to commit all its data.
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.
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. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details and example usage.
The default implementation requests interaction and sends a close event to all visible top level widgets. If any event was rejected, the shutdown is cancelled.
See also isSessionRestored(), sessionId() and saveState().
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.
See also setCursorFlashTime().
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: canvas/main.cpp, desktop/desktop.cpp, helpviewer/main.cpp, i18n/main.cpp, qmag/qmag.cpp, qwerty/main.cpp and scribble/main.cpp.
See also setDesktopSettingsAware().
The default value on X11 is 400 milliseconds. On Windows, the control panel value is used.
See also setDoubleClickInterval().
See also exit_loop() and loopLevel().
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: biff/main.cpp, fonts/simple-qfont-demo/simple-qfont-demo.cpp, life/main.cpp, t1/main.cpp, t4/main.cpp, table/statistics/main.cpp and xml/outliner/main.cpp.
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.
Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.
Example: picture/picture.cpp.
See also enter_loop() and loopLevel().
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.
See also flushX(), sendPostedEvents() and QPainter::flush().
See also syncX().
Example: xform/xform.cpp.
Returns the application widget that has the keyboard input focus, or 0 if no widget in this application has the focus.
See also QWidget::setFocus(), QWidget::focus and activeWindow().
See also setFont(), fontMetrics() and QWidget::font.
Examples: qfd/fontdisplayer.cpp, themes/metal.cpp and themes/themes.cpp.
See also font(), setFont(), QWidget::fontMetrics() and QPainter::fontMetrics().
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.
See also setGlobalStrut().
This signal is emitted when the GUI thread is about to process a cycle of the event loop.
See also wakeUpGuiThread().
Returns TRUE if global mouse tracking is enabled; otherwise returns FALSE.
See also setGlobalMouseTracking().
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.
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.
See also removeTranslator(), translate() and QTranslator::load().
Example: i18n/main.cpp.
By default, Qt will try to use the desktop settings. Call setDesktopSettingsAware(FALSE) to prevent this.
See also setEffectEnabled() and Qt::UIEffect.
Returns TRUE if the application has been restored from an earlier session; otherwise returns FALSE.
See also sessionId(), commitData() and saveState().
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: action/main.cpp, addressbook/main.cpp, application/main.cpp, helpviewer/main.cpp, mdi/main.cpp, qwerty/main.cpp and showimg/main.cpp.
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 also setLibraryPaths(), addLibraryPath(), removeLibraryPath() and QLibrary.
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.
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.
See also enter_loop() and exit_loop().
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.
Returns the main application widget, or 0 if there is no main widget.
See also setMainWidget().
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:
See also QObject::event() and installEventFilter().
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().
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: desktop/desktop.cpp, themes/metal.cpp and themes/wood.cpp.
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().
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(), QThread::postEvent() and notify().
You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file).
Example: fileiconview/qfileiconview.cpp.
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).
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.
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: addressbook/main.cpp, helpviewer/main.cpp, qwerty/main.cpp, showimg/main.cpp, t2/main.cpp, t4/main.cpp and t6/main.cpp.
This method is non-portable. It is available only in Qt/Embedded.
See also QWSDecoration.
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.
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.
This method is non-portable. It is available only in Qt/Embedded.
See also QWSDecoration.
See also addLibraryPath(), libraryPaths() and setLibraryPaths().
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.
See also installTranslator(), translate() and QObject::tr().
Example: i18n/main.cpp.
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().
Example: showimg/showimg.cpp.
See also setReverseLayout().
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 example, 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.
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.
Warning: 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().
Sends event event directly to receiver receiver, using the notify() function. Returns the value that was returned from the event handler.
The event is not deleted when the event has been sent. The normal approach is to create the event on the stack, e.g.
QMouseEvent me( QEvent::MouseButtonPress, pos, 0, 0 ); QApplication::sendEvent( mainWindow, &me );If you create the event on the heap you must delete it.
See also postEvent() and notify().
Example: popup/popup.cpp.
Note that events from the window system are not dispatched by this function, but by processEvents().
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.
The session identifier is guaranteed to be unique both for different applications and for different instances of the same application.
See also isSessionRestored(), commitData() and saveState().
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.
The color specification must be set before you create the QApplication object.
The options 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 attractive.
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.
* 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: helpviewer/main.cpp, showimg/main.cpp, t9/main.cpp, tetrix/tetrix.cpp and themes/main.cpp.
Note that on Microsoft Windows, calling this function sets the cursor flash time for all windows.
See also cursorFlashTime().
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 the main() function might look like this:
int 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.
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().
Note that on Microsoft Windows, calling this function sets the double click interval for all windows.
See also doubleClickInterval().
See also isEffectEnabled(), Qt::UIEffect and setDesktopSettingsAware().
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.
See also font(), fontMetrics() and QWidget::font.
Examples: desktop/desktop.cpp, qfd/qfd.cpp, showimg/main.cpp, themes/metal.cpp and themes/themes.cpp.
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.
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::mouseTracking.
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.
The strut size should be considered when reimplementing GUI controls that may be used on touch-screens or similar IO-devices.
Example:
QSize& WidgetClass::sizeHint() const { return QSize( 80, 25 ).expandedTo( QApplication::globalStrut() ); }
See also globalStrut().
See also libraryPaths(), addLibraryPath(), removeLibraryPath() and QLibrary.
In most respects the main widget is like any other widget, except that if it is deleted, the application exits.
You need not have 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: biff/main.cpp, canvas/main.cpp, fonts/simple-qfont-demo/simple-qfont-demo.cpp, life/main.cpp, t1/main.cpp, t4/main.cpp and xml/outliner/main.cpp.
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 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.
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::cursor.
Example: showimg/showimg.cpp.
The palette may be changed according to the current GUI style in QStyle::polish().
See also QWidget::palette, palette() and QStyle::polish().
Examples: i18n/main.cpp, themes/metal.cpp, themes/themes.cpp and themes/wood.cpp.
See also reverseLayout().
See also startDragDistance().
See also startDragTime().
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().
Example: themes/themes.cpp.
Uses QStyleFactory to create a QStyle object for style.
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().
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().
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().
Qt also uses this delay internally, e.g. in QTextView and QLineEdit, for starting a drag.
The default value is 500 ms.
See also setStartDragTime() and startDragDistance().
See also closingDown().
See also setStyle() and QStyle.
See also flushX().
The list is created using new and must be deleted by the caller.
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.
See also allWidgets(), QWidget::isTopLevel, QWidget::visible and QPtrList::isEmpty().
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.
See also QObject::tr(), installTranslator() and defaultCodec().
Attempts to lock the Qt library mutex, and returns immediately. If the lock was obtained, this function returns TRUE. If another thread has locked the mutex, this function returns FALSE, instead of waiting for the lock to become available.
The mutex must be unlocked with unlock() before another thread can successfully lock it.
See also lock(), unlock() and Thread Support in Qt.
Unlock the Qt library mutex. If wakeUpGui is TRUE (the default), then the GUI thread will be woken with QApplication::wakeUpGuiThread().
See also lock(), locked() and Thread Support in Qt.
Wakes up the GUI thread.
See also guiThreadAwake() and Thread Support in Qt.
See also setWheelScrollLines().
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().
Returns a pointer to the widget at global screen position pos, or 0 if there is no Qt widget there.
If child is FALSE and there is a child widget at position pos, the top-level widget containing it is returned. If child is TRUE the child widget at position pos is returned.
Returns the color used to mark selections in windows style.
See also setWinStyleHighlightColor().
Returns the version of the Windows operating system that is running:
Note that this function is implemented for the Windows version of Qt only.
If you create an application that inherits QApplication and reimplement this function, you get direct access to all X events that the are received from the X server.
Return TRUE if you want to stop the event from being processed. Return FALSE for normal event dispatching.
See also x11ProcessEvent().
It returns 1 if the event was consumed by special handling, 0 if the event was consumed by normal handling, and -1 if the event was for an unrecognized widget.
See also x11EventFilter().
This is really a macro defined in qglobal.h.
Q_ASSERT is useful for testing required conditions in your program.
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.
This is really a macro defined in qglobal.h.
Example:
int *a; Q_CHECK_PTR( a = new int[80] ); // never do this! // do this instead: a = new int[80]; Q_CHECK_PTR( a ); // this is fine
See also qFatal() and Debugging.
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.
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).
See also qWarning(), qFatal(), qInstallMsgHandler() and Debugging.
Prints a fatal error message msg 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.
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.
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.
Prints the message msg and uses code to get a system specific error message. When code is -1 (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.
Prints a warning 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:
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.
This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.
Copyright © 2002 Trolltech | Trademarks | Qt version 3.0.4
|