Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

TQApplication Class Reference

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

#include <qapplication.h>

Inherits TQObject.

List of all member functions.

Public Members

Public Slots

Signals

Static Public Members

Related Functions


Detailed Description

The TQApplication 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's initialization and finalization, and provides session management. It also handles most system-wide and application-wide settings.

For any GUI application that uses TQt, there is precisely one TQApplication object, no matter whether the application has 0, 1, 2 or more windows at any time.

The TQApplication object is accessible through the global pointer qApp. Its main areas of responsibility are:

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

Since the TQApplication 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.)

Groups of functions
System settings desktopSettingsAware(), setDesktopSettingsAware(), cursorFlashTime(), setCursorFlashTime(), doubleClickInterval(), setDoubleClickInterval(), wheelScrollLines(), setWheelScrollLines(), palette(), setPalette(), font(), setFont(), fontMetrics().
Event handling exec(), processEvents(), enter_loop(), exit_loop(), exit(), quit(). sendEvent(), postEvent(), sendPostedEvents(), removePostedEvents(), hasPendingEvents(), notify(), macEventFilter(), qwsEventFilter(), x11EventFilter(), x11ProcessEvent(), winEventFilter().
GUI Styles style(), setStyle(), polish().
Color usage colorSpec(), setColorSpec(), qwsSetCustomColors().
Text handling installTranslator(), removeTranslator() translate().
Widgets mainWidget(), setMainWidget(), allWidgets(), topLevelWidgets(), desktop(), activePopupWidget(), activeModalWidget(), clipboard(), focusWidget(), winFocus(), activeWindow(), widgetAt().
Advanced cursor handling hasGlobalMouseTracking(), setGlobalMouseTracking(), overrideCursor(), setOverrideCursor(), restoreOverrideCursor().
X Window System synchronization flushX(), syncX().
Session management isSessionRestored(), sessionId(), commitData(), saveState().
Threading lock(), unlock(), locked(), tryLock(), wakeUpGuiThread()
Miscellaneous closeAllWindows(), startingUp(), closingDown(), type().

Non-GUI programs: While TQt is not optimized or designed for writing non-GUI programs, it's possible to use some of its classes without creating a TQApplication. 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.


Member Type Documentation

TQApplication::ColorSpec

See setColorSpec() for full details.

TQApplication::Encoding

This enum type defines the 8-bit encoding of character string arguments to translate():

See also TQObject::tr(), TQObject::trUtf8(), and TQString::fromUtf8().

TQApplication::Type


Member Function Documentation

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

Initializes the window system and constructs an application object with argc command line arguments in 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 (including widgets, pixmaps, bitmaps etc.).

Note that argc and argv might be changed. TQt removes command line arguments that it recognizes. The modified argc and argv can also be accessed later with qApp->argc() and qApp->argv(). The documentation for argv() contains a detailed description of how to process command line arguments.

TQt debugging options (not available if TQt was compiled with the QT_NO_DEBUG flag defined):

See Debugging Techniques for a more detailed explanation.

All TQt programs automatically support the following command line options:

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

See also argc() and argv().

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

Constructs an application object with argc command line arguments in argv. If GUIenabled is TRUE, a GUI application is constructed, otherwise a non-GUI (console) 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 and Macintosh, currently the window system is always initialized, regardless of the value of GUIenabled. This may change in future versions of TQt.

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
    TQApplication app(argc, argv, useGUI);

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

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

Constructs an application object with argc command line arguments in argv.

For TQt/Embedded, passing TQApplication::GuiServer for type makes this application the server (equivalent to running with the -qws option).

TQApplication::TQApplication ( Display * dpy, HANDLE visual = 0, HANDLE colormap = 0 )

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

Warning: TQt only supports TrueColor visuals at depths higher than 8 bits-per-pixel.

This is available only on X11.

TQApplication::TQApplication ( Display * dpy, int argc, char ** argv, HANDLE visual = 0, HANDLE colormap = 0 )

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

Warning: TQt only supports TrueColor visuals at depths higher than 8 bits-per-pixel.

This is available only on X11.

TQApplication::~TQApplication () [virtual]

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

void TQApplication::aboutTQt () [slot]

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

This is useful for inclusion in the Help menu of an application. See the examples/menu/menu.cpp example.

This function is a convenience slot for TQMessageBox::aboutTQt().

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

TQWidget * TQApplication::activeModalWidget () [static]

Returns the active modal widget.

A modal widget is a special top level widget which is a subclass of TQDialog 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().

TQWidget * TQApplication::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 TQPopupMenu 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().

TQWidget * TQApplication::activeWindow () const

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 TQWidget::setFocus(), TQWidget::focus, and focusWidget().

Example: network/mail/smtp.cpp.

void TQApplication::addLibraryPath ( const TQString & 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.

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 TQt was installed.

See also removeLibraryPath(), libraryPaths(), and setLibraryPaths().

TQWidgetList * TQApplication::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 (TQPtrList::isEmpty()) if there are no widgets.

Note that some of the widgets may be hidden.

Example that updates all widgets:

    TQWidgetList  *list = TQApplication::allWidgets();
    TQWidgetListIt it( *list );         // iterate over the widgets
    TQWidget * w;
    while ( (w=it.current()) != 0 ) {  // for each widget...
        ++it;
        w->update();
    }
    delete list;                      // delete the list, not the widgets
  

The TQWidgetList 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(), TQWidget::visible, and TQPtrList::isEmpty().

TQString TQApplication::applicationDirPath ()

Returns the directory that contains the application executable.

For example, if you have installed TQt in the C:\Trolltech\TQt directory, and you run the demo example, this function will return "C:/Trolltech/TQt/examples/demo".

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

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.

See also applicationFilePath().

TQString TQApplication::applicationFilePath ()

Returns the file path of the application executable.

For example, if you have installed TQt in the C:\Trolltech\TQt directory, and you run the demo example, this function will return "C:/Trolltech/TQt/examples/demo/demo.exe".

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.

See also applicationDirPath().

int TQApplication::argc () const

Returns the number of command line arguments.

The documentation for argv() describes how to process command line arguments.

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

Examples: chart/main.cpp and scribble/scribble.cpp.

char ** TQApplication::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 TQApplication object is constructed by passing argc and argv from the main() function. Some of the arguments may be recognized as TQt options and removed from the argument vector. For example, the X11 version of TQt 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 )
        {
            TQApplication a( argc, argv );
            TQListBox 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".

TQt provides a global pointer, qApp, that points to the TQApplication object, and through which you can access argc() and argv() in functions other than main().

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

Examples: chart/main.cpp and scribble/scribble.cpp.

void TQApplication::beep () [static]

Sounds the bell, using the default volume and sound.

TQClipboard * TQApplication::clipboard () [static]

Returns a pointer to the application global clipboard.

Examples: regexptester/regexptester.cpp and showimg/showimg.cpp.

void TQApplication::closeAllWindows () [slot]

Closes all top-level windows.

This function is particularly useful for applications with many top-level windows. It could, for example, be connected to a "Quit" entry in the file menu as shown in the following code example:

    // the "Quit" menu entry should try to close all windows
    TQPopupMenu* file = new TQPopupMenu( 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 TQWidget::close(), TQWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(), and TQWidget::isTopLevel.

Examples: action/application.cpp, application/application.cpp, helpviewer/helpwindow.cpp, mdi/application.cpp, and qwerty/qwerty.cpp.

bool TQApplication::closingDown () [static]

Returns TRUE if the application objects are being destroyed; otherwise returns FALSE.

See also startingUp().

int TQApplication::colorSpec () [static]

Returns the color specification.

See also TQApplication::setColorSpec().

Example: showimg/showimg.cpp.

void TQApplication::commitData ( TQSessionManager & sm ) [virtual]

This function deals with session management. It is invoked when the TQSessionManager 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 TQSessionManager::allowsInteraction() and TQSessionManager::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 canceled.

See also isSessionRestored(), sessionId(), saveState(), and the Session Management overview.

int TQApplication::cursorFlashTime () [static]

Returns the text cursor's flash (blink) time in milliseconds. The flash time is the time retquired 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 be changed at any time by the user changing the global desktop settings.

See also setCursorFlashTime().

TQTextCodec * TQApplication::defaultCodec () const

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Returns TQTextCodec::codecForTr().

TQDesktopWidget * TQApplication::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, since this does not work on all operating systems.

    TQDesktopWidget *d = TQApplication::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.

bool TQApplication::desktopSettingsAware () [static]

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

See also setDesktopSettingsAware().

int TQApplication::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 TQApplication::enter_loop ()

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

This function enters the main event loop (recursively). Do not call it unless you really know what you are doing.

Use TQApplication::eventLoop()->enterLoop() instead.

TQEventLoop * TQApplication::eventLoop () [static]

Returns the application event loop. This function will return zero if called during and after destroying TQApplication.

To create your own instance of TQEventLoop or TQEventLoop subclass create it before you create the TQApplication object.

See also TQEventLoop.

Example: distributor/distributor.ui.h.

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

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 TQMessageBox 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 TQTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

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

Examples: helpsystem/main.cpp, life/main.cpp, network/archivesearch/main.cpp, network/ftpclient/main.cpp, opengl/main.cpp, t1/main.cpp, and t4/main.cpp.

void TQApplication::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.

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: chart/chartform.cpp, extension/mainform.ui.h, and picture/picture.cpp.

void TQApplication::exit_loop ()

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

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

Use TQApplication::eventLoop()->exitLoop() instead.

void TQApplication::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.

See also flushX(), sendPostedEvents(), and TQPainter::flush().

void TQApplication::flushX () [static]

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

See also syncX().

Example: xform/xform.cpp.

TQWidget * TQApplication::focusWidget () const

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

See also TQWidget::setFocus(), TQWidget::focus, and activeWindow().

TQFont TQApplication::font ( const TQWidget * 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 TQWidget::font.

Examples: qfd/fontdisplayer.cpp, themes/metal.cpp, and themes/themes.cpp.

TQFontMetrics TQApplication::fontMetrics () [static]

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

See also font(), setFont(), TQWidget::fontMetrics(), and TQPainter::fontMetrics().

TQSize TQApplication::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.

See also setGlobalStrut().

void TQApplication::guiThreadAwake () [signal]

This signal is emitted after the event loop returns from a function that could block.

See also wakeUpGuiThread().

bool TQApplication::hasGlobalMouseTracking () [static]

Returns TRUE if global mouse tracking is enabled; otherwise returns FALSE.

See also setGlobalMouseTracking().

bool TQApplication::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 TQApplication::postEvent().

int TQApplication::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.

void TQApplication::installTranslator ( TQTranslator * mf )

Adds the message file mf to the list of message files to be used for translations.

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

Example: i18n/main.cpp.

bool TQApplication::isEffectEnabled ( TQt::UIEffect effect ) [static]

Returns TRUE if effect is enabled; otherwise returns FALSE.

By default, TQt 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 TQt::UIEffect.

bool TQApplication::isSessionRestored () const

Returns TRUE if the application has been restored from an earlier session; otherwise returns FALSE.

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

void TQApplication::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(), TQWidget::isTopLevel, and TQWidget::close().

Examples: addressbook/main.cpp, extension/main.cpp, helpviewer/main.cpp, mdi/main.cpp, network/archivesearch/main.cpp, qwerty/main.cpp, and regexptester/main.cpp.

TQStringList TQApplication::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 TQt 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.

    TQStringList list = app.libraryPaths();
    TQStringList::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 TQLibrary.

void TQApplication::lock ()

Lock the TQt 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 TQt.

bool TQApplication::locked ()

Returns TRUE if the TQt 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 TQt.

int TQApplication::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 TQApplication::eventLoop()->loopLevel() instead.

bool TQApplication::macEventFilter ( EventHandlerCallRef, EventRef ) [virtual]

This virtual function is only implemented under Macintosh.

If you create an application that inherits TQApplication 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.

TQWidget * TQApplication::mainWidget () const

Returns the main application widget, or 0 if there is no main widget.

See also setMainWidget().

bool TQApplication::notify ( TQObject * receiver, TQEvent * 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:

  1. Reimplementing this function. This is very powerful, providing complete control; but only one subclass can be qApp.

  2. 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 reimplementing notify(); 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.

  3. Reimplementing TQObject::event() (as TQWidget 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 event filter gets all the events except Tab and Shift-Tab key presses.

  5. Reimplementing paintEvent(), mousePressEvent() and so on. This is the commonest, easiest and least powerful way.

See also TQObject::event() and installEventFilter().

TQCursor * TQApplication::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().

TQPalette TQApplication::palette ( const TQWidget * 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 TQWidget::palette.

Examples: desktop/desktop.cpp, themes/metal.cpp, and themes/wood.cpp.

void TQApplication::polish ( TQWidget * 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 TQWidget. Instead, based on meta information like TQObject::className() you are able to customize any kind of widget.

See also TQStyle::polish(), TQWidget::polish(), setPalette(), and setFont().

void TQApplication::postEvent ( TQObject * receiver, TQEvent * event ) [static]

Note: This function is thread-safe when TQt is built withthread 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 TQApplication::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(), TQTimer, and TQEventLoop::processEvents().

Examples: fileiconview/qfileiconview.cpp and network/ftpclient/main.cpp.

void TQApplication::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(), TQTimer, and TQEventLoop::processEvents().

void TQApplication::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 TQt 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 TQTimer.

void TQApplication::quit () [slot]

Tells the application to exit with return code 0 (success). Equivalent to calling TQApplication::exit( 0 ).

It's common to connect the lastWindowClosed() signal to quit(), and you also often connect e.g. TQButton::clicked() or signals in TQAction, TQPopupMenu or TQMenuBar to it.

Example:

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

See also exit(), aboutToQuit(), lastWindowClosed(), and TQAction.

Examples: addressbook/main.cpp, mdi/main.cpp, network/archivesearch/main.cpp, regexptester/main.cpp, t2/main.cpp, t4/main.cpp, and t6/main.cpp.

TQWSDecoration & TQApplication::qwsDecoration () [static]

Return the TQWSDecoration used for decorating windows.

This method is non-portable. It is available only in TQt/Embedded.

See also TQWSDecoration.

bool TQApplication::qwsEventFilter ( TQWSEvent * ) [virtual]

This virtual function is only implemented under TQt/Embedded.

If you create an application that inherits TQApplication and reimplement this function, you get direct access to all TQWS (Q Window System) events that the are received from the TQWS master process.

Return TRUE if you want to stop the event from being processed. Return FALSE for normal event dispatching.

void TQApplication::qwsSetCustomColors ( TQRgb * colorTable, int start, int numColors )

Set TQt/Embedded custom color table.

TQt/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 TQWS 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 TQt/Embedded.

void TQApplication::qwsSetDecoration ( TQWSDecoration * d ) [static]

Set the TQWSDecoration derived class to use for decorating the TQt/Embedded windows to d.

This method is non-portable. It is available only in TQt/Embedded.

See also TQWSDecoration.

void TQApplication::removeLibraryPath ( const TQString & 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 TQApplication::removePostedEvents ( TQObject * receiver ) [static]

Note: This function is thread-safe when TQt is built withthread 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 TQApplication::removeTranslator ( TQTranslator * mf )

Removes the message file mf from the list of message files used by this application. (It does not delete the message file from the file system.)

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

Example: i18n/main.cpp.

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

Examples: distributor/distributor.ui.h, network/archivesearch/archivedialog.ui.h, network/ftpclient/ftpmainwindow.ui.h, and showimg/showimg.cpp.

bool TQApplication::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 TQApplication::saveState ( TQSessionManager & 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 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 TQSessionManager::allowsInteraction() and TQSessionManager::allowsErrorInteraction() for details.

See also isSessionRestored(), sessionId(), commitData(), and the Session Management overview.

bool TQApplication::sendEvent ( TQObject * receiver, TQEvent * event ) [static]

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.

    TQMouseEvent me( TQEvent::MouseButtonPress, pos, 0, 0 );
    TQApplication::sendEvent( mainWindow, &me );
    
If you create the event on the heap you must delete it.

See also postEvent() and notify().

Example: popup/popup.cpp.

void TQApplication::sendPostedEvents ( TQObject * receiver, int event_type ) [static]

Immediately dispatches all events which have been previously queued with TQApplication::postEvent() and which are for the object receiver and have the event type event_type.

Note that events from the window system are not dispatched by this function, but by processEvents().

If receiver is null, the events of event_type are sent for all objects. If event_type is 0, all the events are sent for receiver.

void TQApplication::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.

TQString TQApplication::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.

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

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

TQString TQApplication::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.

The session key changes with every call of commitData() or saveState().

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

void TQApplication::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.

The color specification must be set before you create the TQApplication 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 )
  {
      TQApplication::setColorSpec( TQApplication::ManyColor );
      TQApplication a( argc, argv );
      ...
  }
  

TQColor provides more functionality for controlling color allocation and freeing up certain colors. See TQColor::enterAllocContext() for more information.

To check what mode you end up with, call TQColor::numBitPlanes() once the TQApplication object exists. A value greater than 8 (typically 16, 24 or 32) means true color.

* The color cube used by TQt 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(), TQColor::numBitPlanes(), and TQColor::enterAllocContext().

Examples: helpviewer/main.cpp, opengl/main.cpp, showimg/main.cpp, t9/main.cpp, tetrax/tetrax.cpp, tetrix/tetrix.cpp, and themes/main.cpp.

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

Sets the text cursor's flash (blink) time to msecs milliseconds. The flash time is the time retquired 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.

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

See also cursorFlashTime().

void TQApplication::setDefaultCodec ( TQTextCodec * 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 TQTextCodec::setCodecForTr().

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

By default, TQt 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.

This static function must be called before creating the TQApplication object, like this:

  int main( int argc, char** argv ) {
    TQApplication::setDesktopSettingsAware( FALSE ); // I know better than the user
    TQApplication myApp( argc, argv ); // Use default fonts & colors
    ...
  }
  

See also desktopSettingsAware().

void TQApplication::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 TQApplication::setEffectEnabled ( TQt::UIEffect effect, bool enable = TRUE ) [static]

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

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

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

void TQApplication::setFont ( const TQFont & 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 may adjust themselves to the new application setting. If informWidgets is FALSE, the change only affects newly created widgets. If className is passed, the change applies only to classes that inherit className (as reported by TQObject::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.

See also font(), fontMetrics(), and TQWidget::font.

Examples: desktop/desktop.cpp, themes/metal.cpp, and themes/themes.cpp.

void TQApplication::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.

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 TQWidget::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
        TQApplication::setGlobalMouseTracking( TRUE );
        TQApplication::setGlobalMouseTracking( TRUE );
        TQApplication::setGlobalMouseTracking( FALSE );
        // at this point it's still on
        TQApplication::setGlobalMouseTracking( FALSE );
        // but now it's off
    

See also hasGlobalMouseTracking() and TQWidget::mouseTracking.

void TQApplication::setGlobalStrut ( const TQSize & strut ) [static]

Sets the application's global strut to 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.

The strut size should be considered when reimplementing GUI controls that may be used on touch-screens or similar IO-devices.

Example:

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

See also globalStrut().

void TQApplication::setLibraryPaths ( const TQStringList & paths ) [static]

Sets the list of directories to search when loading libraries to paths. All existing paths will be deleted and the path list will consist of the paths given in paths.

See also libraryPaths(), addLibraryPath(), removeLibraryPath(), and TQLibrary.

void TQApplication::setMainWidget ( TQWidget * mainWidget ) [virtual]

Sets the application's main widget to mainWidget.

In most respects the main widget is like any other widget, except that if it is closed, the application exits. Note that TQApplication does not take ownership of the mainWidget, so if you create your main widget on the heap you must delete it yourself.

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 TQWidget::setGeometry()) before calling setMainWidget().

See also mainWidget(), exec(), and quit().

Examples: chart/main.cpp, helpsystem/main.cpp, life/main.cpp, network/ftpclient/main.cpp, opengl/main.cpp, t1/main.cpp, and t4/main.cpp.

void TQApplication::setOverrideCursor ( const TQCursor & 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 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:

        TQApplication::setOverrideCursor( TQCursor(TQt::WaitCursor) );
        calculateHugeMandelbrot();              // lunch time...
        TQApplication::restoreOverrideCursor();
    

See also overrideCursor(), restoreOverrideCursor(), and TQWidget::cursor.

Examples: distributor/distributor.ui.h, network/archivesearch/archivedialog.ui.h, network/ftpclient/ftpmainwindow.ui.h, and showimg/showimg.cpp.

void TQApplication::setPalette ( const TQPalette & 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.

If className is passed, the change applies only to widgets that inherit className (as reported by TQObject::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 TQStyle::polish().

See also TQWidget::palette, palette(), and TQStyle::polish().

Examples: i18n/main.cpp, themes/metal.cpp, themes/themes.cpp, and themes/wood.cpp.

void TQApplication::setReverseLayout ( bool b ) [static]

If b is TRUE, all dialogs and widgets will be laid out in a mirrored fashion, as retquired by right to left languages such as Arabic and Hebrew. If b is FALSE, dialogs and widgets are laid out left to right.

Changing this flag in runtime does not cause a relayout of already instantiated widgets.

See also reverseLayout().

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

Sets the distance after which a drag should start to l pixels.

See also startDragDistance().

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

Sets the time after which a drag should start to ms ms.

See also startDragTime().

void TQApplication::setStyle ( TQStyle * style ) [static]

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

Example usage:

    TQApplication::setStyle( new TQWindowsStyle );
  

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(), TQStyle, setPalette(), and desktopSettingsAware().

Example: themes/themes.cpp.

TQStyle * TQApplication::setStyle ( const TQString & style ) [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Requests a TQStyle object for style from the TQStyleFactory.

The string must be one of the TQStyleFactory::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 TQApplication 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 TQStyle object returned is set as the application's GUI style.

void TQApplication::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.

See also wheelScrollLines().

void TQApplication::setWinStyleHighlightColor ( const TQColor & 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 TQApplication::startDragDistance () [static]

If you support drag and 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.

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() >
       TQApplication::startDragDistance() )
    startTheDrag();
  

TQt uses this value internally, e.g. in TQFileDialog.

The default value is 4 pixels.

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

int TQApplication::startDragTime () [static]

If you support drag and 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 the delay (in ms).

TQt also uses this delay internally, e.g. in TQTextEdit and TQLineEdit, for starting a drag.

The default value is 500 ms.

See also setStartDragTime() and startDragDistance().

bool TQApplication::startingUp () [static]

Returns TRUE if an application object has not been created yet; otherwise returns FALSE.

See also closingDown().

TQStyle & TQApplication::style () [static]

Returns the application's style object.

See also setStyle() and TQStyle.

void TQApplication::syncX () [static]

Synchronizes with the X server in the X11 implementation. This normally takes some time. Does nothing on other platforms.

See also flushX().

TQWidgetList * TQApplication::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 (TQPtrList::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.
    TQWidgetList  *list = TQApplication::topLevelWidgets();
    TQWidgetListIt it( *list );  // iterate over the widgets
    TQWidget * 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(), TQWidget::isTopLevel, TQWidget::visible, and TQPtrList::isEmpty().

TQString TQApplication::translate ( const char * context, const char * sourceText, const char * comment = 0, Encoding encoding = DefaultCodec ) const

Note: This function is reentrant when TQt 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.

TQObject::tr() and TQObject::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 TQTranslator 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 TQString 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 TQTranslator.

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.

See also TQObject::tr(), installTranslator(), and defaultCodec().

bool TQApplication::tryLock ()

Attempts to lock the TQt 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 TQt.

Type TQApplication::type () const

Returns the type of application, Tty, GuiClient or GuiServer.

void TQApplication::unlock ( bool wakeUpGui = TRUE )

Unlock the TQt Library Mutex. If wakeUpGui is TRUE (the default), then the GUI thread will be woken with TQApplication::wakeUpGuiThread().

See also lock(), locked(), and Thread Support in TQt.

void TQApplication::wakeUpGuiThread ()

Wakes up the GUI thread.

See also guiThreadAwake() and Thread Support in TQt.

int TQApplication::wheelScrollLines () [static]

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

See also setWheelScrollLines().

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

Returns a pointer to the widget at global screen position (x, y), or 0 if there is no TQt 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 TQCursor::pos(), TQWidget::grabMouse(), and TQWidget::grabKeyboard().

TQWidget * TQApplication::widgetAt ( const TQPoint & 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 TQt 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.

bool TQApplication::winEventFilter ( MSG * ) [virtual]

This virtual function is only implemented under Windows.

The message procedure calls this function for every message received. Reimplement this function if you want to process window messages that are not processed by TQt. If you don't want the event to be processed by TQt, then return TRUE; otherwise return FALSE.

void TQApplication::winFocus ( TQWidget * widget, bool gotFocus )

This function is available only on Windows.

If gotFocus is TRUE, widget will become the active window. Otherwise the active window is reset to NULL.

const TQColor & TQApplication::winStyleHighlightColor () [static]

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Returns the color used to mark selections in windows style.

See also setWinStyleHighlightColor().

bool TQApplication::x11EventFilter ( XEvent * ) [virtual]

This virtual function is only implemented under X11.

If you create an application that inherits TQApplication 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().

int TQApplication::x11ProcessEvent ( XEvent * event )

This function does the core processing of individual X events, normally by dispatching TQt events to the right destination.

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


Related Functions

void Q_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.

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 ( TQtCleanUpFunction p )

Adds a global routine that will be called from the TQApplication 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 TQApplication destructor is called, for example.

For modules and libraries, using a reference-counted initialization manager or TQt' 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 TQObject {
    private:
        MyPrivateInitStuff( TQObject * parent ): TQObject( parent) {
            // initialization goes here
        }
        MyPrivateInitStuff * p;

    public:
        static MyPrivateInitStuff * initStuff( TQObject * 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 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 *)0 as argument to qDebug might lead to crashes on certain platforms due to the platforms printf implementation.

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 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 *)0 as argument to qFatal might lead to crashes on certain platforms due to the platforms printf implementation.

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

TQtMsgHandler qInstallMsgHandler ( TQtMsgHandler h )

Installs a TQt 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 TQt 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( TQtMsgType type, const char *msg )
        {
            switch ( type ) {
                case TQtDebugMsg:
                    fprintf( stderr, "Debug: %s\n", msg );
                    break;
                case TQtWarningMsg:
                    fprintf( stderr, "Warning: %s\n", msg );
                    break;
                case TQtFatalMsg:
                    fprintf( stderr, "Fatal: %s\n", msg );
                    abort();                    // deliberately core dump
            }
        }

        int main( int argc, char **argv )
        {
            qInstallMsgHandler( myMessageOutput );
            TQApplication 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.

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 TQt is built with QT_NO_DEBUG defined.

const char * qVersion ()

Returns the TQt version number as a string, for example, "2.3.0" or "3.0.5".

The QT_VERSION define has the numeric value in the form: 0xmmiibb (m = major, i = minor, b = bugfix). For example, TQt 3.0.5's QT_VERSION is 0x030005.

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

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

Warning: Passing (const char *)0 as argument to qWarning might lead to crashes on certain platforms due to the platforms printf implementation.

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


This file is part of the TQt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.


Copyright © 2007 TrolltechTrademarks
TQt 3.3.8